self referential struct definition? self referential struct definition? c c

self referential struct definition?


Clearly a Cell cannot contain another Cell as it becomes a never-ending recursion.

However a Cell CAN contain a pointer to another Cell.

typedef struct Cell {  bool isParent;  struct Cell* child;} Cell;


In C, you cannot reference the typedef that you're creating withing the structure itself. You have to use the structure name, as in the following test program:

#include <stdio.h>#include <stdlib.h>typedef struct Cell {  int cellSeq;  struct Cell* next; /* 'tCell *next' will not work here */} tCell;int main(void) {    int i;    tCell *curr;    tCell *first;    tCell *last;    /* Construct linked list, 100 down to 80. */    first = malloc (sizeof (tCell));    last = first;    first->cellSeq = 100;    first->next = NULL;    for (i = 0; i < 20; i++) {        curr = malloc (sizeof (tCell));        curr->cellSeq = last->cellSeq - 1;        curr->next = NULL;        last->next = curr;        last = curr;    }    /* Walk the list, printing sequence numbers. */    curr = first;    while (curr != NULL) {        printf ("Sequence = %d\n", curr->cellSeq);        curr = curr->next;    }    return 0;}

Although it's probably a lot more complicated than this in the standard, you can think of it as the compiler knowing about struct Cell on the first line of the typedef but not knowing about tCell until the last line :-) That's how I remember that rule.


From the theoretical point of view, Languages can only support self-referential structures not self-inclusive structures.