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

How can I open a file so that other programs can update it at the same time?

648


Why do we use int main?

590


Who is the main contributor in designing the c language after dennis ritchie?

532


‘SAVEPOINT’ and ‘ROLLBACK’ is used in oracle database to secure the data comment. Give suitable examples of each with sql command.

1865


What is the best style for code layout in c?

618






What is the purpose of void pointer?

586


What is #include cctype?

566


What is the general form of function in c?

603


What is an auto variable in c?

736


What would happen to X in this expression: X += 15; (assuming the value of X is 5)

1282


why to assign a pointer to null sometimes??how can a pointer we declare get assigned with a garbage value by default???

1505


What is bss in c?

590


Can we declare function inside main?

553


What is putchar() function?

619


Explain c preprocessor?

667