Dark Mode

2,217 views

8 votes

What is printed by the following $\text{ANSI C}$ program?

#include<stdio.h> int main(int argc, char *argv[]) { int x = 1, z[2] = {10, 11}; int *p = NULL; p = &x; *p = 10; p = &z[1]; *(&z[0] + 1) += 3; printf(“%d, %d, %d\n”, x, z[0], z[1]); return 0; }

- $1, 10, 11$
- $1, 10, 14$
- $10, 14, 11$
- $10, 10, 14$

10 votes

Option D is correct answer.

Given that x=1, z[0]=10 and z[1]=11

int *p=NULL; p=&x; *p=10;

By this code, they are accessing x and changing it’s value to 10. Therefore x=10 after the above code executed.

*(&z[0]+1) += 3;

$\text{ [ As per precedence rule, z[0], &z[0], &z[0]+1, *(&z[0]+1) and *(&z[0]+1) += 3; evaluated in the order ] }$

&z[0] --- address of z[0]

&z[0] + 1 ---- address of z[1] $\text{ [ because z[0] and z[1] are contiguously allocated in the memory ]}$

So, we can rewrite the above statement as *( address of z[1] ) += 3

which is nothing but z[1] += 3 ==> z[1] = z[1] + 3

Therefore z[1] = 14

Notice that, z[0] not changed.

1 vote

the correct answer is option “D”

now let me explain how?

4^{th} line is normal, assigning the values to int x and an array “z”

*p is a pointer and initially its value is null or 0. now in the 6^{th} line, we store or assign the address of “x” into “p”.

now in the pointer, we update the value from null or 0 to 10. since the pointer is pointing to “int x” therefore the value of int x will also change to 10. now we update the pointer to z[1] or {11}. now at last *(&z[0] + 1) += 3 ==> (&z[0]+1 means value at address z[0]+1, which is 11……. 11+3=14) here value of z[1] will update to 14

now printf(“%d, %d, %d\n”, x, z[0], z[1]) will print 10,10,14