ProgrammingHardIBM · Deloitte pattern

Assume a 64-bit LP64 ABI. What is printed?

Assume a 64-bit LP64 ABI. What is printed?
struct A { int x; };
struct B { struct A a; int y; };
struct B b = {{10}, 20};
struct A *pa = (struct A *)&b;
printf("%d %d", pa->x, ((int *)&b)[1]);
  1. A. 10 10
  2. B. 10 20
  3. C. 20 10
  4. D. 20 20

Correct answer: B. 10 20

Thanks to the 'common initial sequence' guarantee and the fact that struct A is the very first member of struct B with no padding before it, a pointer to struct B reinterpreted as struct A* legally accesses the same memory as b.a; pa->x reads 10. Treating &b as an int* and indexing [1] skips past the first 4-byte int (b.a.x) and reads the next 4 bytes, which is b.y = 20.

More C Programming questions

Exams that ask this topic