Dhiraj Barnwal Dhiraj Barnwal - 1 month ago 5
C Question

Size of a self referential structure

I have some doubt regarding what the size of a self referential structure in C is. I ran the following code and it gave me a output of 24

#include<stdio.h>

int main() {

struct hello {
int a;
char ch[10];
struct hello *p;
} dhiraj;

printf("%d",sizeof(struct hello));
return 0;
}


Now next I modified the index of ch and made it 20 the next time and after running it gave on output of 32

The other weird behavior which I noted was that after the execution of the following code -

#include<stdio.h>

int main() {

struct hello {
int a;
// int b; Statement 1
// int c; Statement 2
struct hello *p;
} dhiraj;

printf("%d",sizeof(struct hello));
return 0;
}


I got an output of 16. After activating statement 1 the output was still 16 but after activating both statement 1 and statement 2 the output became 24. What is actually happening here ?

Answer

What you're running into is data structure padding. Data is handled in word size chunks, on a 64 bit computer this is probably 8 bytes. This means your structs will be padded to a multiple of 8.

struct hello {
    int a;
    char ch[10];
    struct hello *p;
}

Assuming you're on a 64 bit machine with 64 bit pointers, that is 4 + 10 + 8 = 22. 22 isn't a multiple of 8, so sizeof(struct hello) gets padded out to 24. Change it to ch[12] and you'll still get 24. Change it to ch[13] and the size will jump to 32.

This is a bit oversimplified, but you get the idea.