I am used to code like below for long.
But how does C compiler resolve the circular definition issue? Or does that issue really exist?
struct node {
int data;
struct node *next; // circular definition for "struct node" type?
};
Or, on a 32-bit machine, can I somewhat treat struct node * next member just as a member of 32-bit unsigned integer type? That makes me feel better.
The reason I think of circular definition is, when compiler encounters something like next -> data or next -> next, it has to know the exact offset of each member to add to the next pointer to get the correct location of each member. And that kind of calculation requires knowledge of each member's type. So for the member next, the circular definition issue may arise:
The type of
nextisstruct node *, thestruct nodetype contains anext, the type ofnextisstruct node *...
And how does the compiler calculate the sizeof(struct node)?
Well, I think the critical concept to understand this seemingly circular issue is, a pointer's size is not relevant to what type it points to. And the size is fixed on a specific machine. A pointer's type is only meaningful at compile-time for the compiler to generate instructions for pointer calculation.
next is a struct node *, which is just a pointer, not a struct node, so there's no actual circular definition. The details of a struct aren't required to figure out how to make a pointer to it.
To address your addenda:
struct node and struct node * are entirely different types. A struct node * doesn't contain any other objects.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With