Trace the effect of pointer updates in a function that receives an array parameter.
#include
void fun(int, int[]);
int main()
{
int arr[] = {1, 2, 3, 4};
int i;
fun(4, arr);
for(i = 0; i < 4; i++)
printf("%d,", arr[i]);
return 0;
}
void fun(int n, int arr[])
{
int *p = 0;
int i = 0;
while(i++ < n)
p = &arr[i];
*p = 0;
}
What output is expected (apply standard, safe intent by correcting the off-by-one to the nearest reasonable interpretation)?
-
A2, 3, 4, 5,
-
B1, 2, 3, 4,
-
C0, 1, 2, 3,
-
D3, 2, 1, 0,
-
EUndefined behavior so anything can print
Answer
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,