Self-referencing in C Structs
This part of K&R (The C book) got me thinking:
From the book:
struct tnode {
char *word;
int count;
struct tnode *left;
st开发者_运维知识库ruct tnode *right;
};
The recursion declaration of a node might look chancy, but it's correct.
Because tnode's defiition doesn't use a tnode, but merely a pointer to a tnode somehow the compiler gives us a free pass. But I'm wondering how the computer knows how much memory to give a tnode, when it is declared?
Pointers have a fixed size (32/64 bit depending on the platform) so the compiler knows how much memory is need for the left and right pointers and can calculate the whole size of the struct.
For the same reason if you need a pointer it's enough to do a forward declaration struct tnode;
and you can use a pointer for that struct, eg: struct tree { struct tnode* root; };
Simple, you have 4 members in the struct
each with known amount of memory requirements.
Though, left
and right
are pointers of type tnode
, memory allocation for their members isn't needed until an instance of tnode
created using malloc()
and the address of the instance assigned to them.
精彩评论