Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is printed by the following ANSI C program?

#include\(\lt\)stdio.h\(\gt\)
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;
}

  • A.1, 10, 11
  • B.1, 10, 14
  • C.10, 14, 11
  • D.10, 10, 14

Answer: D

The program prints 10, 10, 14.

  1. p = &x; *p = 10; writes 10 into x through the pointer.
  2. p = &z[1]; only moves p; nothing is written.
  3. &z[0] + 1 is the address of z[1], so *(&z[0] + 1) += 3 adds 3 to z[1], making it 14. z[0] stays 10.

So x = 10, z[0] = 10, z[1] = 14. '1, 10, 11' and '1, 10, 14' forget that x was changed through p. '10, 14, 11' applies the += 3 to z[0] instead of to the element one past it.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.