In C pointer arithmetic with post-increment on pointers, assume &x = 500 and sizeof(int) = 4 bytes. What prints? #include<stdio.h> int main() { int x = 30, *y, z; y = &x; / &x is 500 */ z = y; *y++ = *z++; x++; printf("x=%d, y=%d, z=%d ", x, y, z); return 0; }

Difficulty: Medium

Correct Answer: x=31, y=504, z=504

Explanation:


Introduction / Context:
This evaluates post-increment on pointers combined with dereferencing and assignment. It also highlights that printing pointers with %d is nonportable, but within this exercise we treat them as integer addresses to show arithmetic on int *.


Given Data / Assumptions:

  • &x is 500 (artificial base for demonstration).
  • sizeof(int) = 4 bytes.
  • Both pointers y and z are initially &x.
  • Expression *y++ = z++; means (y++) = *(z++).


Concept / Approach:
Post-increment returns the original pointer for the dereference, then increments the pointer by one element. Thus the assignment copies the current value at &x to itself and then both pointers advance to point past x by 4 bytes (since they are int *).


Step-by-Step Solution:
Initial: x = 30; y = z = 500.*y++ = *z++ → reads *(500) = 30 and stores to *(500) = 30 (no change to x); then y = z = 504.x++ → x becomes 31.printf prints x and the new pointer values: x=31, y=504, z=504.


Verification / Alternative check:
Rewrite with temporaries: *y = *z; y = y + 1; z = z + 1; where pointer increments add sizeof(int).


Why Other Options Are Wrong:
(a) uses +2 which is not correct for 4-byte ints. (b) keeps pointers at 500 despite post-increment. (c) subtracts; not applicable. (e) adds +8 as if two increments or larger element size had occurred.


Common Pitfalls:
Parsing *y++ as (*y)++ (it is not); forgetting that pointer arithmetic scales by element size.


Final Answer:
x=31, y=504, z=504

More Questions from Pointers

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion