Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C structure with pointer to self [duplicate]

Tags:

c

struct

Is it posible to define a structure with a pointer to that type of structure? What I mean is:

typedef struct {
    char* name;
    node* parent;
} node;

As far as I tried or read, I don't know how to do this or if it's even possible.

like image 331
shazarre Avatar asked Nov 28 '09 22:11

shazarre


People also ask

Can a structure contain a pointer to itself in C?

Yes such structures are called self-referential structures.

Can you structure contain pointer to itself?

Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member.

How do I copy a structure pointer to another?

Re: Copying structures containing pointers Normally, we can copy the structures in a two way. obj2=obj1; obj2. x1 = malloc(5*sizeof(int)); * And you can copy the structure using memcpy.

Can you copy one structure into another in C?

A nested structure in C is a structure within structure. One structure can be declared inside another structure in the same way structure members are declared inside a structure.


2 Answers

Yes, but you have to name the structure, so that you can refer to it.

typedef struct node_ {
    char* name;
    struct node_ * parent;
} node;

The name node only becomes declared after the structure is fully defined.

like image 113
avakar Avatar answered Oct 06 '22 03:10

avakar


You can use an incomplete type in the typedef:

typedef struct node node;

struct node {
  char *name;
  node *parent;
};
like image 40
sambowry Avatar answered Oct 06 '22 05:10

sambowry