Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 725
James Adams Avatar asked Oct 18 '14 04:10

James Adams


Video Answer


1 Answers

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]);
 }
like image 139
Jayesh Bhoi Avatar answered Sep 24 '22 05:09

Jayesh Bhoi