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;
There is sort of a way around this:
struct Cell {
bool isParent;
struct Cell* child;
};
struct Cell;
typedef struct Cell Cell;
If you declare it like this, it properly tells the compiler that struct Cell and plain-ol'-cell are the same. So you can use Cell just like normal. Still have to use struct Cell inside of the initial declaration itself though.
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.