arrayscpointerspass-by-referencefunction-parameter

Why does this function not modify the original array when passed as a parameter?


#include <stdio.h>


void modifyArray(int arr[]) {
    arr = (int[]){6, 7, 8, 9, 10}; // Trying to modify the array
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    modifyArray(arr);
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]); // Outputs 1 2 3 4 5, not 6 7 8 9 10
    }
}

Expected Output: 6 7 8 9 10

Actual Output: 1 2 3 4 5

Why does the original array remain unchanged, and how can I modify it correctly?


Solution

  • An array, whenever used in a function parameter declaration, gets adjusted to a pointer to the first element. In your case the code is equivalent to void modifyArray(int* arr).

    And that's why the code works in the first place - C does not allow assignments of arrays. Instead arr = (int[]){6, 7, 8, 9, 10}; re-assigns the local variable arr from pointing at the passed array, to pointing at a compound literal. When the function ends, the local variable is gone, so the caller side remains unaffected.

    To modify the array you'd have to use memcpy or similar - to actually access the contents of the pointed-at array.