/* struct_addr.c - To prepare for our discussion of 3.5 derived data types, * and the completion of lab 9 (centroid) and hw1 (word stats), let's look * more closely at struct and their starting addresses. How are they * aligned? How are the fields aligned? */ #include struct place { char c1; int i; char s[5]; float f; double d; char c2; }; main() { struct place a[10]; int i; printf("The struct itself has a size of %d.\n", sizeof(struct place)); printf("Addresses of each element and field:\n"); printf(" # base c1 i s f d c2\n"); for (i = 0; i < 10; ++i) printf("%2d: %08x %08x %08x %08x %08x %08x %08x\n", i, &a[i], &a[i].c1, &a[i].i, &a[i].s, &a[i].f, &a[i].d, &a[i].c2); // Conclusions printf("sizeof(char) = %d\n", sizeof(char)); printf("sizeof(int) = %d\n", sizeof(int)); printf("sizeof(float) = %d\n", sizeof(float)); printf("sizeof(double) = %d\n", sizeof(double)); printf("Space allocated to c1 = %d\n", (int)&a[0].i - (int)&a[0].c1); printf("Space allocated to i = %d\n", (int)&a[0].s - (int)&a[0].i); printf("Space allocated to s = %d\n", (int)&a[0].f - (int)&a[0].s); printf("Space allocated to f = %d\n", (int)&a[0].d - (int)&a[0].f); printf("Space allocated to d = %d\n", (int)&a[0].c2 - (int)&a[0].d); printf("Space allocated to c2 = %d\n", (int)&a[1].c1 - (int)&a[0].c2); } /* Example output: The struct itself has a size of 40. Addresses of each element and field: # base c1 i s f d c2 0: 70223400 70223400 70223404 70223408 70223410 70223418 70223420 1: 70223428 70223428 7022342c 70223430 70223438 70223440 70223448 2: 70223450 70223450 70223454 70223458 70223460 70223468 70223470 3: 70223478 70223478 7022347c 70223480 70223488 70223490 70223498 4: 702234a0 702234a0 702234a4 702234a8 702234b0 702234b8 702234c0 5: 702234c8 702234c8 702234cc 702234d0 702234d8 702234e0 702234e8 6: 702234f0 702234f0 702234f4 702234f8 70223500 70223508 70223510 7: 70223518 70223518 7022351c 70223520 70223528 70223530 70223538 8: 70223540 70223540 70223544 70223548 70223550 70223558 70223560 9: 70223568 70223568 7022356c 70223570 70223578 70223580 70223588 sizeof(char) = 1 sizeof(int) = 4 sizeof(float) = 4 sizeof(double) = 8 Space allocated to c1 = 4 Space allocated to i = 4 Space allocated to s = 8 Space allocated to f = 8 Space allocated to d = 8 Space allocated to c2 = 8 */