// (typical 32 bit machine)
// char 1 byte
// short int 2 bytes
// int 4 bytes
// double 8 bytes
// structure A
typedef struct structa
{
char c;
short int s;
} structa_t;
// structure B
typedef struct structb
{
short int s;
char c;
int i;
} structb_t;
// structure C
typedef struct structc
{
char c;
double d;
int s;
} structc_t;
// structure D
typedef struct structd
{
double d;
int s;
char c;
} structd_t;
int main()
{
printf("sizeof(structa_t) = %d\n", sizeof(structa_t));
printf("sizeof(structb_t) = %d\n", sizeof(structb_t));
printf("sizeof(structc_t) = %d\n", sizeof(structc_t));
printf("sizeof(structd_t) = %d\n", sizeof(structd_t));
return 0;
}
What should be the o/p and explain it..
how can we prevent this erroneous behavior.
In dev c++ ,it's giving output as 4 8 24 16 but in linux which also has gcc compiler ,it gives output as 4 8 16 16 .I think it depends on the OS.You plz explain the solution as this is really difficult to understand the concept of sizeof(structure).
ReplyDelete@above the output will be different for different compilers with different set of flags set.
ReplyDeleteIn above problem:
A double (eight bytes) will be 8-byte aligned on Windows and 4-byte aligned on Linux (8-byte with -malign-double compile time option).
Sorry! Can u plz be more elaborate? What are different flags set for compilers and what is 8 byte with -mailgn-double compile time option?
ReplyDelete@above different compilers behave differently on same piece of code because of different flag set in them.If we talk of gcc they perform certain optimization based on certain flag set and -malign double is one of them,which when set double becomes 8 bytes aligned otherwise 4 bytes aligned.You can look for other compiler flags here ..
ReplyDeletehttp://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html