retagged by
5,701 views
12 votes
12 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. $1, 10, 11$
  2. $1, 10, 14$
  3. $10, 14, 11$
  4. $10, 10, 14$
retagged by

3 Answers

16 votes
16 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.

edited by
2 votes
2 votes

the correct answer is option “D”


now let me explain how?

4th 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 6th 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

 

0 votes
0 votes
  1. int x = 1, z[2] = {10, 11};
  2. // Initially they are intialized one integer and one 1D array in the above statement//
  3. int *p = NULL;
  4. // here they initializing one integer pointer and assigning the address as null//
  5. p = &x;
  6. //here they are assigning address of x to the p //
  7. *p = 10;
  8. // here they are changing the value as 10 at the address of p is pointing // 
  9. Through this statement x will become 10
  10. p = &z[1];
  11. // now they are assigning address of 2nd element to the pointer p,by dereferencing previous address//
  12. *(&z[0] + 1) += 3;
  13. // &z[0] means 1st element address //
  14.   &z[0]+1 means next element of &z[0] i.e 2nd element in the array
  15. *(&z[0]+1) the value present at that address i.e 11(the value of second element in the array)
  16. by using assignment operator *(&z[0]+1)=*(&z[0]+1)+3 is equal 11+3=14(it is replaces the second element in the array as 14)
  17. printf(“%d, %d, %d\n”, x, z[0], z[1]);
  18. Answer: x=10,z[0]=10,z[1]=14.
Answer:

Related questions