How to avoid structure padding in C?

Answer Posted / lokesh mogra

yes u can use pragma to change change byte alignment.
for e.g.
typedef struct _s1{
unsigned int i;
unsigned char c;
unsigned long a;
unsigned short e;
} s1;
Size of this structure is of 11 Bytes. but due to default
byte alignment(8 byte) which is different for different
compilers. The size of structure would be 16 Bytes.
In order to change the alignment, we will have to do
something like this.

#pragma pack(push,1)
typedef struct _s1{
unsigned int i;
unsigned char c;
unsigned long a;
unsigned short e;
//unsigned char b;
} s1;
#pragma pack(pop)

This will change the byte alignment to 1 Byte. and thus size
of structure will be exactly 11 bytes

Is This Answer Correct ?    49 Yes 11 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain what is the benefit of using #define to declare a constant?

696


Difference between exit() and _exit() function?

761


Explain how do you generate random numbers in c?

721


Why c is a procedural language?

697


Why c is called a mid level programming language?

695






Explain modulus operator.

689


What is c basic?

715


Why do we use header files in c?

686


What is the equivalent code of the following statement in WHILE LOOP format?

895


Difference between pass by reference and pass by value?

740


What is the function of this pointer?

772


Is that possible to add pointers to each other?

998


PLS U SENS ME INTERVIEW O. MY EMAIL ADD, SOFIYA.SINGH@GMAIL.COM

1823


What are different types of operators?

685


Why do we need functions in c?

648