The size of structure in C

The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.

Different compilers might have different alignment constraints as C standards state that alignment of structure totally depends on the implementation.

  • Case 1:
 1struct A {    
 2	// sizeof(int) = 4 
 3    int x; 
 4    // Padding of 4 bytes 
 5
 6    // sizeof(double) = 8 
 7    double z; 
 8    
 9    // sizeof(short int) = 2 
10    short int y; 
11    // Padding of 6 bytes 
12}; 

Output:

​ Size of struct: 24

Output1

The red portion represents the padding added for data alignment and the green portion represents the struct members. In this case, x (int) is followed by z (double), which is larger in size as compared to x. Hence padding is added after x. Also, padding is needed at the end for data alignment.

  • Case 2:
 1struct B { 
 2    // sizeof(double) = 8 
 3    double z; 
 4    
 5    // sizeof(int) = 4 
 6    int x; 
 7    
 8    // sizeof(short int) = 2 
 9    short int y; 
10    // Padding of 2 bytes 
11}; 

Output:

​ Size of struct: 16

output2

In this case, the members of the structure are sorted in decreasing order of their sizes. Hence padding is required only at the end.

  • Case 3:
 1struct C { 
 2    // sizeof(double) = 8 
 3    double z; 
 4    
 5    // sizeof(short int) = 2 
 6    short int y; 
 7    // Padding of 2 bytes 
 8    
 9    // sizeof(int) = 4 
10    int x; 
11}; 

Output:

​ Size of struct: 16

output3

In this case, y (short int) is followed by x (int) and hence padding is required after y. No padding is needed at the end in this case for data alignment.

C language doesn’t allow the compilers to reorder the struct members to reduce the amount of padding. In order to minimize the amount of padding, the struct members must be sorted in a descending order (similar to the case 2).