Search code examples
carrayspointersimmutabilitymutability

Passing an array as a function argument from within a function which takes it as an argument in C


G'day!

If I have a function which takes an array of ints as an argument, and then from within that function, send off that same array to another function, will it still be able to edit the array values and have them be committed at a main level rather than at a function level?

i.e

int
main(int argc, char *argv[]) {
    int A[50];
    functionB(A);
 }

where function B looks like:

void functionB(int A[]) {
    functionC(A);
}

and function C is the one which actually mutates the values within A[].

Would main see the changed array or the original A[]?

Thanks!


Solution

  • Array decays to pointer. So it will modify the original array.

    Check it

    void functionC(int A[]) {
        A[0] = 1;
        A[1] = 2;
    }
    
    void functionB(int A[]) {
        functionC(A);
    }
    
    int
    main(int argc, char *argv[]) {
        int A[2]={5,5};
    
        printf("Before call: %d  %d\n",A[0],A[1]);
        functionB(A);
        printf("After call : %d  %d\n",A[0],A[1]);
     }