Assume int is 4 bytes. What does the following C program print?
#include <stdio.h>
int main(void) {
int a[6] = {4, 9, 2, 7};
int *p = a + 3;
int *q = &a[1];
*q += *p;
p--;
*p = p - q;
printf("%d %d %d", a[1], a[2], *(q + 3));
return 0;
}
Show solution
Solution MCQ · 1 mark · −⅓ if wrong
Answer: (A) 16 1 0
Method. Lay the array out with indices and follow each pointer as an index.
| index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| start | 4 | 9 | 2 | 7 | 0 | 0 |
The initialiser lists four values, so a[4] and a[5] are 0.
p = a + 3points to index 3;q = &a[1]points to index 1.*q += *p:a[1] = 9 + 7 = 16.p--:pnow points to index 2.*p = p - q: the difference of twoint *is the number of elements between them, , soa[2] = 1.*(q + 3)is index , which holds 0.
Output: 16 1 0.
The trap. Pointer subtraction is scaled by the element size, so it gives 1 here, not 4 bytes; the "int is 4 bytes" line is there to tempt exactly that slip. Also, q + 3 is relative to q (index 1), not to the start of the array.
What was tested. Pointer arithmetic in units of elements, the difference between writing through a pointer (*q += ...) and moving it (p--), and zero-filling of a partially initialised array.
Copied. Paste it into the new chat.Too long to send. Copy the question and solution by hand.