Sizeof(struct) = size of individual members + padding

Here we discuss the packing options of the structure. By default, 32bit compilers have structure packing option 4. This option can be modified by

#pragma pack(n)
The required packing option is represented by n and may take values 1, 2, 4 etc. This packing option will overwrite the existing packing option. To preserve the existing packing option, we must save existing packing option by 'push' and then after declaration we 'pop' the original packing option. Following example shows this:
#pragma pack( push, before_include1 )
#include "include1.h"
#pragma pack( pop, before_include1 )

Size calculation:
With the packing value 1, the structure size is the sum of the sizes of the members. For packing value of more than 1, we must consider the padding size. Padding fills the extra space between the last member and the packing value.

#pragma pack(1)
struct user
{
  unsigned int id;
  unsigned char paid;
};
size = sizeof(unsigned int) + sizeof(unsigned char) 
     = 4 + 1 
     = 5;
	 
#pragma pack(4)
struct user
{
  unsigned int id;
  unsigned char paid;
};
size = sizeof(unsigned int) + sizeof(unsigned char) + padding 
     = 4 + 1 + 3
     = 8;

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#