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

Discussion

What will be the following C code print ?

int a[] = {1,2,3,4};
int *p = a ;
printf("%d", *(++p) + 2);

  • A.3
  • B.4
  • C.5
  • D.Compilation error : invalid use of in crement operators on pointer dereference

Answer: B

The program prints 4.

  1. int *p = a; makes p point at a[0], which holds 1.
  2. ++p is a pre-increment, so p moves to a[1] before it is used.
  3. *(++p) therefore reads a[1], which is 2.
  4. 2 + 2 gives 4, printed with %d.

3 is what you get from *p + 2 without the increment (1 + 2). 5 would need p to move two places, to a[2], which holds 3. There is no compilation error: incrementing a pointer variable is legal, and the parentheses make the increment apply to p before the dereference.

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

Post your comment

Please log in or register to post a comment.