Reputation: 823
I have written a simple structure program. Here is the code of the program which I have written to print the size of the variables declared inside the structure-
#include<stdio.h>
main()
{
struct book
{char name[10];
int pages;
float price;
}b1={"Blue",500,200.00};
printf("The Address Of Name Is = %d ",&b1.name);
printf("\nThe Address Of Pages Is = %d",&b1.pages);
printf("\nThe Address Of Price Is = %d",&b1.price);
}
Now the problem arises when I Compile the program and run it. I get the size of the CHARACTER array printed as 12 bytes instead of the 10 bytes. Here is the output -
blueelvis@Blueelvis:~$ ./a.out
The Address Of Name Is = 1264893904
The Address Of Pages Is = 1264893916
The Address Of Price Is = 1264893920
Could someone please explain why this is happening? Also note that I am running in Linux environment.
Upvotes: 0
Views: 109
Reputation: 7775
This is because of Data Structure Alignment which means that the compiler will insert padding between variables in a class/struct to make sure that the next variable falls on an optimal boundary for memory access. This is different for each type.
There is a full explanation here in this answer: Why isn't sizeof for a struct equal to the sum of sizeof of each member?
But for your case, the alignment of an integer is 4
, so it rounds your 10
up to 12
. i.e. there is padding between the char[]
and the int
to make sure the integer starts on a 4 byte boundary.
Upvotes: 1