C / C++ FAQs & Programming Resources - ProkutFAQ : PassingArrayArguments

HomePage Recent Changes Recently Commented Login/Register

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
 Comments [Hide comments/form]
Correction to Second Program :-

void myFunction(int(*)[4][4]);
-- 203.34.117.5 (2009-08-08 13:07:31)
Thanks, now I have updated with correct prototype for second program.
-- SharathAV (2009-08-08 18:17:41)
op oproggopi gjorrgporg r
-- ras.beamtele.net (2013-02-12 12:28:44)
Page was generated in 0.0484 seconds