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;

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

 Vote 0

Similar topics related to this section

typedef, struct type, union type, struct vs union, struct pack padding, size of a structure, bit fields, l-value, struct and array, function declaration and definition,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan