Everything Else

Passing a multi-dimensional array to a function in C

I wanted to pass a multi-dimensional array to a function in C. As in, directly manipulate the contents of an array passed as a parameter.

After many hours of messing around with pointers and getting nowhere, I decided maybe I was trying to be too complicated and tried the following :

Code: Select all

#include <stdio.h>

void changeArray(int testarray[2][2])
{
testarray[1][1]=3;
}

void changeInt(int test)
{
test=4;
}


int main()
{
int array[2][2] = { {1,1}, {1,1} };
int myint=1;

printf("%i %i\n",array[1][1],myint);
changeArray(array);
changeInt(myint);
printf("%i %i\n",array[1][1],myint);


}


Sure enough, the result was :

Code: Select all

$ ./PointerTest
1 1
3 1
$


myint works as I expected C to work. What I don't understand is why the multi-dimensional array is treated differently?

Thanks for any help you can give.
When you call "changeInt(myint)", a copy of myint is made.
When you call "void changeArray(array)" a pointer to array is passed to the function.

That's why the content of the array is changed.
the specific reason is that, except when used as the argument to operator& or sizeof(), array expressions are converted to a pointer to their first element.
This is handy for C's function calling rules, which do not allow array types to be passed to, or returned from functions.
:PI: :O2: :Indigo2IMP: :Indigo2IMP:
Thank you both for your replies. So, how would I pass a multi-dimensional array of unknown dimensions to a function? Using [][]?
Use a pointer int*, pass inner dimension as argument and access it like array[i * width + j]. (the compiler will complain about passing int[][] as int*, I'm not sure how portable it is).


This:

Code: Select all

void changeInt(int test)
{
test=4;
}


does exactly nothing.
:PI: :Indigo: :Indigo: :Indigo: :Indy: :Indy: :Indigo2: :Indigo2IMP: :Octane: :Fuel: :540: Image
If the function does not know the dimensions you will need to pass those in, and if you have an arbitrary number of dimensions those need to be passed in an array along with another count of the number of dimensions.
Land of the Long White Cloud and no Software Patents.