When an array is passed as parameter to a function, which of the following…
2014
When an array is passed as parameter to a function, which of the following statements is correct ?
- A.
The function can change values in the original array.
- B.
In C, parameters are passed by value, the function cannot change the original value in the array.
- C.
It results in compilation error when the function tries to access the elements in the array.
- D.
Results in a run time error when the function tries to access the elements in the array.
Attempted by 562 students.
Show answer & explanation
Correct answer: A
Answer: The function can change values in the original array.
Explanation: When an array is passed to a function in C, it decays to a pointer to its first element. The function receives that pointer (the pointer value is passed by value), and using that pointer to index or dereference elements modifies the original array memory.
Array name decays to a pointer to the first element when passed as a parameter.
The pointer itself is passed by value: reassigning the parameter inside the function does not change the caller's pointer, but modifying the data it points to does affect the original array.
Out-of-bounds access causes undefined behavior and may lead to runtime errors, but passing an array normally does not cause compile- or run-time errors.
Example:
void func(int arr[]) {
arr[0] = 10; // modifies the original array element
}
int main() {
int a[3] = {1, 2, 3};
func(a);
// a[0] is now 10
return 0;
}
Note: Modifying elements within bounds updates the original array. Reassigning the parameter pointer itself does not change the caller's pointer variable.