Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C resolve circular definition when a pointer in struct points to the struct itself?

Tags:

c

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?
};

ADD 1

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.

ADD 2

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 next is struct node *, the struct node type contains a next, the type of next is struct node *...

ADD 3

And how does the compiler calculate the sizeof(struct node)?

ADD 4

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.

like image 506
smwikipedia Avatar asked Dec 19 '25 00:12

smwikipedia


1 Answers

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:

  1. Although that's more or less accurate and will probably work, it's not guaranteed by the standard, and you shouldn't do it.
  2. Again, struct node and struct node * are entirely different types. A struct node * doesn't contain any other objects.
like image 156
Joseph Sible-Reinstate Monica Avatar answered Dec 20 '25 18:12

Joseph Sible-Reinstate Monica