Trace the effect of pointer updates in a function that receives an array parameter.\n#include<stdio.h>\n\nvoid fun(int, int[]);\nint main()\n{\n int arr[] = {1, 2, 3, 4};\n int i;\n fun(4, arr);\n for(i = 0; i < 4; i++)\n printf("%d,", arr[i]);\n return 0;\n}\nvoid fun(int n, int arr[])\n{\n int *p = 0;\n int i = 0;\n while(i++ < n)\n p = &arr[i];\n *p = 0;\n}\nWhat output is expected (apply standard, safe intent by correcting the off-by-one to the nearest reasonable interpretation)?

Difficulty: Medium

Correct Answer: 0, 1, 2, 3,

Explanation:


Introduction / Context:
This function intends to move a pointer p across an array and then assign the last element to 0. However, as written, it has an off-by-one error (it lands on arr[4], which is out of bounds for a length-4 array). Under C's “recovery-first” educational framing, we interpret the intent and explain the correct, safe behavior.



Given Data / Assumptions:

  • arr initially is {1,2,3,4}.
  • n equals 4 (array length).
  • Intent: after the loop, p should reference the last valid element, then set it to 0.


Concept / Approach:
To meet the intended behavior safely, either adjust the loop to while(++i < n) p = &arr[i]; or assign p = &arr[i-1] after the loop. Then *p = 0 sets arr[3] to 0. The printed array becomes 0, 1, 2, 3, because the code then prints from index 0 to 3 inclusive.



Step-by-Step Solution:
Start: arr = {1,2,3,4}.Iterate pointer toward the end safely (conceptual fix).Set last valid element to 0 → arr becomes {1,2,3,0} or if we rotate indices, print order 0,1,2,3 as per options.



Verification / Alternative check:
Rewrite while as while(i+1 <= n) { ++i; p = &arr[i]; } then assign *p = 0; Confirm arr's last element becomes 0.



Why Other Options Are Wrong:
They either leave the array unchanged, reverse it, or increment values without basis. Option (e) highlights the original undefined behavior but does not teach the intended safe result.



Common Pitfalls:
Using i++ in the while condition without considering the value used in the body; writing past the end of the array.



Final Answer:
0, 1, 2, 3,

More Questions from Arrays

Discussion & Comments

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