Ambiguous output of C program

#include<stdio.h>
struct test{
int a;
double b;
char c;
};
typedef struct test structure;
int main()
{
printf("%d\n",sizeof(structure));
}
According to me this code should print 13. But it is showing 24, please explain.

3 Likes

For faster access, the compiler inserts dummy bits between the elements of a structure. This is called Structure Packing. The elements are placed at integral multiples of data type size or pack size (usually 8 bytes), whichever is smallest. In your case the largest data type double has 8 bytes so the elements are placed after an 8 bytes. So, 8*******3= 24.
If your structure had been:

struct test{

int a;

char c;

};

The largest data type in this case would be int of 4 bytes. So size of structure would be 4*****2=8.

Structure packing is done to enable faster access of elements when an array of structure is created. However, to manually disable structure packing you can insert these two lines before and after structure declaration:

#pragma pack(push, 1)

struct test

{

int a;

double b;

char c;

};

#pragma pack(pop)

which will give the size of structure as 13.

9 Likes

Awesome! This was a new information :slight_smile:

2 Likes