How can we pass 2 or 3 dimensional array as argument to function?
You could use pointer to array for that purpose.
Passing 2 dimensional array
Example:
/* This program demonstrates passing a 2 dimensional array of size 4 * 4 */
void myFunction(int(*)[4]);
int main()
{
int a[4][4];
myFunction(a);
return 0;
}
void myFunction(int (*myArray)[4])
{
/* Here you can access the content of the argument passed like any other 2-D array */
/* Example: myArray[2][2]=10; */
}
Passing 3 dimensional array
Example:
/* This program demonstrates passing a 3 dimensional array of size 4 * 4 * 4 */
void myFunction(int(*)[4][4]);
int main()
{
int a[4][4][4];
myFunction(a);
return 0;
}
void myFunction(int (*myArray)[4][4])
{
/* Here you can access the content of the argument passed like any other 3-D array */
/* Example: myArray[2][2][2]=10; */
}
Note:
Since the function is accessing the array using pointer, when you make modification to the array values in myFunction, it makes modification in the original array in main function. If you don't want this to happen, the other way around is to wrap the array in a structure, and pass the structure object to function.
CategoryPointers