Wednesday, 2 July 2008

How to pass a multi-dimensional array as reference to a function??

If you have a multi-dimensional data, e.g. two-dimensional array, say

int mydata[10][20];

and you would like to pass it as reference to another function in C++, say

int myfunc (int data[][])
{
//got mydata[10][20] here..
//do whatever you like to mydata[10][20]
}

How can you do it? well, in C++, it is not easy to handle multi-dimensional array (Weired...why? I DON'T KNOW, but it is the TRUTH!). Well, you may always re-organize the data to a 1D array and simply pass pointer of that array...(which seems easier), but you have to remember the way you put them to 1D, and well, you have to re-organize back to multi-dimensional array after you passed inside the function....I don't prefer that....So, isn't there way that can pass multi-dimensional array as it was to a function?

Well, luckily we have STL, the standard template library. We may define a two-dimensional array by using the vector class in STL, e.g.

> my2Darray(10, vector(20,0));
//this will initialize an 2D array with initial values set to 0;

and then you may pass the 2D array as reference to a function, like this,

void myfunc ( >& anyname)
{
//well, the 2D array "anyname" is already passed inside!
//you may do whatever on it...
//e.g. print out one of its element...
cout<< my2Darray[1][2]<
//firstly define a 2D array, or you may assign other values...

> my2Darray(10, vector(20,0));

//then call myfunc

myfunc(my2Darray);

return 0;

}

You will see the output of print out of my2Darray[1][2];

Bingo!

No comments: