Pragma directive in structure(c)

simran nagdeo
2 min readJan 3, 2021

According to the memory allocation strategy of operating system, the memory gets allocated in terms of WORD size(4bytes for 32bit machine).

If the member of the structure is less than WORD size then the remaining memory gets wasted which is considered as padding(It is the allocated memory which is not usable).

We can use the concept of pragma directive to avoid the memory wastage due to padding.

eg.

struct Demo{

int i;

char ch;

float f;

double d;

};

According to the above diagram of memory layout, the structure gets 20 bytes of memory where 17 bytes are required, that means 3 bytes are considered as wastage that is padding.

To avoid that, we declare the above structure as,

#pragma pack(1)

struct Demo{

int i;

char ch;

float f;

double d;

};

Restrictions and Limitations of #pragma pack:

  1. The statement of #pragma pack should be written before the declaration of a structure.
  2. If the statement is written after declaration of structure then there is no such effect of #pragma pack.
  3. In the parameter of #pragma pack we can specify either 1,2,4,8,16. If we specify 8, then it indicates that we want the memory in terms of 8 bytes. But it is good programming practise to specify 1 as a parameter.

--

--