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]);- A. 10 10
- B. 10 20
- C. 20 10
- 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
- Assume a 64-bit LP64 ABI. What is printed? c struct Flags { unsigned ready : 1; unsigned error : 1; unsigned mode : 2; }; struct Flags f =…
- Assume a 64-bit LP64 ABI. What is printed? c struct Node { int value; struct Node next; }; printf("%zu", sizeof(struct Node));
- Assume a 64-bit LP64 ABI. What is printed? c typedef union { struct { unsigned char r, g, b, a; } channels; unsigned int packed; } Color…
- What is printed? c #define SQUARE(x) x x int main() { int a = 5; printf("%d", SQUARE(a + 1)); }
- What is printed? c #define INCR(x) x++ int main() { int i = 5; int r = 2 INCR(i); printf("%d %d", r, i); }
- What is printed? c #define PR(x) printf(#x " = %dn", x) int main() { int value = 42; PR(value); }