Search code examples
cpointersstructureself-reference

Can any one explain me how the size get allocated in the following case?


I got confused with the size allocation with my gcc compiler, can any one help me how the size get allocated for the following code.

struct node
{
 int data;
 struct node *next;
};

sizeof(struct node) it gives an output as 16.


struct node
{
 int data;
};

sizeof(struct node) it gives an output as 4.


struct node
{
struct node *next;
};

sizeof(struct node) it gives an output as 8.


struct node
{
int data;
struct node *next;
}*link;

sizeof(link) is always 8, even if i add few more elements to structure.



Solution

  • On your specific platform, it looks like an int has size 4 and a pointer has size 8. It also looks like it wants to align pointers on an 8-byte boundary.

    So if struct node just contains an int, then the its size is 4. If it just contains a pointer, its size is 8. If it contains both an int and a pointer, then it needs 12 bytes, but in order to maintain the alignment of the pointer, it pads the structure to a multiple of 8, resulting in a size of 16.

    In your final example, you have link defined as a pointer to a struct node. In this case, it doesn't matter what a struct node contains. Since link is just a pointer, its size will always be 8.

    Again, note that this is just a best guess for your platform. None of this is guaranteed, and it can vary from one platform to another.