Suppose there are five DISTINCT types TYPE1, TYPE2, TYPE3, TYPE4,
TYPE5, of data.
Consider the structures:
struct struct_one
{
TYPE1 data1;
TYPE2 data2;
TYPE3 data3;
TYPE4 data4;
TYPE5 data5;
} var_one;
struct struct_two
{
TYPE2 data1;
TYPE5 data2;
TYPE1 data3;
TYPE3 data4;
TYPE4 data5;
} var_two;
How do the sizes of var_one and var_two compare - will they be the
same or different ?
They could be the same or they could be different. It depends on the
exact types of TYPE* and on the compiler. Compilers can add padding in
order to align fields on their natural boundaries, and there is no
guarantee that one compiler will pack fields the same as another
compiler, especially so when the compilers target different platforms.
Try compiling and running the following:
#include <stddef.h>
#include <stdio.h>
typedef char TYPE1;
typedef double TYPE2;
typedef int TYPE3;
typedef short TYPE4;
typedef long TYPE5;
struct s1
{
TYPE1 d1;
TYPE2 d2;
TYPE3 d3;
TYPE4 d4;
TYPE5 d5;
} var_one;
struct s2
{
TYPE2 d1;
TYPE5 d2;
TYPE1 d3;
TYPE3 d4;
TYPE4 d5;
} var_two;
int main(void)
{
printf("s1 offsets:\n");
printf("offsetof(d1) = %d\n", (int)offsetof(struct s1, d1));
printf("offsetof(d2) = %d\n", (int)offsetof(struct s1, d2));
printf("offsetof(d3) = %d\n", (int)offsetof(struct s1, d3));
printf("offsetof(d4) = %d\n", (int)offsetof(struct s1, d4));
printf("offsetof(d5) = %d\n", (int)offsetof(struct s1, d5));
printf("\n");
printf("s2 offsets:\n");
printf("offsetof(d1) = %d\n", (int)offsetof(struct s2, d1));
printf("offsetof(d2) = %d\n", (int)offsetof(struct s2, d2));
printf("offsetof(d3) = %d\n", (int)offsetof(struct s2, d3));
printf("offsetof(d4) = %d\n", (int)offsetof(struct s2, d4));
printf("offsetof(d5) = %d\n", (int)offsetof(struct s2, d5));
return 0;
}
My conforming C implementation outputs:
s1 offsets:
offsetof(d1) = 0
offsetof(d2) = 8
offsetof(d3) = 16
offsetof(d4) = 20
offsetof(d5) = 24
s2 offsets:
offsetof(d1) = 0
offsetof(d2) = 8
offsetof(d3) = 12
offsetof(d4) = 16
offsetof(d5) = 20
Press any key to continue
Regards