ProgrammingVery hardProduct company OA

Assume 4-byte int with 4-byte alignment. What is printed?

Assume 4-byte int with 4-byte alignment. What is printed?
struct P { char tag; int v; };
struct P a[4] = {{'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}};
struct P *p = a + 1, *q = &a[3];
char *c = (char *)q - sizeof(struct P);
printf("%td %td %d %c", q - p, (char *)q - (char *)p, ((struct P *)c)->v, (p + 1)->tag);
  1. A. 2 10 3 c
  2. B. 16 16 3 c
  3. C. 2 16 3 c
  4. D. 2 16 2 b

Correct answer: C. 2 16 3 c

Pointer subtraction is measured in elements of the pointed-to type: q − p = 2 structs, but after casting to char * the same distance is 2 × sizeof(struct P) = 16 bytes (1 char + 3 padding + 4 int = 8 each). Stepping back one struct size in bytes from &a[3] lands exactly on a[2], whose v is 3; (p + 1) is also a[2], tag 'c'. The option with 10 uses an unpadded size of 5.

More C Programming questions

Exams that ask this topic