Example struct alignment code

8 views
Skip to first unread message

David L. Rager

unread,
Nov 16, 2009, 7:01:20 PM11/16/09
to utexas-cs352-fall2009
You can modify this code to figure out how your compiler aligns data
inside structs.


struct {

char b;
char q[10];
union {
int *p;
char r[6];
int x;
} our_union;
short unsigned int w;
unsigned long l;
short w2;
double f;
} our_struct;


int main ()
{

int struct_size = sizeof( our_struct );

printf("The size of our structure is: %2i.\n", struct_size);

printf(" b: %d\n", (int) &our_struct.b - (int) &our_struct.b);
printf(" q[7]: %d\n", (int) &our_struct.q[7] - (int) &our_struct.b);
printf(" w2: %d\n", (int) &our_struct.w2 - (int) &our_struct.b);
printf(" l: %d\n", (int) &our_struct.l - (int) &our_struct.b);
printf(" x: %d\n", (int) &our_struct.our_union.x - (int) &our_struct.b);
printf(" p: %d\n", (int) &our_struct.our_union.p - (int) &our_struct.b);
printf(" r[3]: %d\n", (int) &our_struct.our_union.r[3] - (int)
&our_struct.b);
printf(" r[-2]: %d\n", (int) &our_struct.our_union.r[-2] -
(int) &our_struct.b);
printf(" w: %d\n", (int) &our_struct.w - (int) &our_struct.b);
printf(" f: %d\n", (int) &our_struct.f - (int) &our_struct.b);
}

Reply all
Reply to author
Forward
0 new messages