C++, How to make a function accept a 2 dimensional array of any size?

Started by
6 comments, last by johnnyBravo 18 years, 9 months ago
Hi with c++, I want to have a function that accepts a two dimensional array of any size. eg float a[3][2] ={{1,2},{5,3},{1,9}}; float b[2][2] ={{5,3},{1,9}}; myFunction(a); myFunction(b); So i tried: void myFunction(float **var);, which doesn't work, i've got a feeling that it probably isn't possible to do this that simply. Is there any simple solution to this? Thanks alot.
Advertisement
I was having this problem a while ago but it was with char[][]. If i remember correctly, the fcn call should look like this:

myFunction( float *var[] );

~guyaton
~guyaton
Here's an example solution that Stroustrup gives.
void print_mij ( int * m, int dim1, int dim2 ){  for ( int i = 0 ; i < dim1 ; i++ )  {    for ( int j = 0 ; j < dim2 ; j++ )    {      cout << m  &lt;&lt; '\t' ;<br>    }<br><br>    cout &lt;&lt; '\n' ;<br>  }<br>}<br><br></pre></div><!–ENDSCRIPT–> 
<span class="smallfont">That is not dead which can eternal lieAnd with strange aeons even death may die.   -- "The Nameless City" - H. P. Lovecraft</span>
That one is just a workaround by transforming a two dimensional array into one with only dimension.

Otherwise it will work and is a common practice.
Note that microdot's solution is in reality a one-dimensional array masquerading as a 2-dimensional array -- it's been pre-packed with the values from the 2d array [EDIT: Yeah, beaten to it :D]. Still, it is a viable solution and may be easier (depending on how you're using it) than...
void myFunction(float **myarray, int dim1, int dim2) { ... }float **a = new float*[3];for (int i = 0; i < 3; i++)    a = new float[2];float **b = new float*[2];for (i = 0; i < 2; i++)    b = new float[2];myFunction(a, 3, 2);myFunction(b, 3, 2);

Once they've been completely initialized, you can access a and b as 2d arrays.
{[JohnE, Chief Architect and Senior Programmer, Twilight Dragon Media{[+++{GCC/MinGW}+++{Code::Blocks IDE}+++{wxWidgets Cross-Platform Native UI Framework}+++
Not sure if this would be relevant for your project but why not encompass the array into a class and pass the address of that class into the function. You can manipulate the array of course with access members, just as if you were manipulating the array itself.
If you are using statically typed arrays, one option is to use templates that accept multidimensional arrays by reference. ex:
template <typename T, int r, int c>void my_function(T (&arr)[r][c]) {  for (int i = 0; i < r; i++) {    for (int j = 0; j < c; j++) {      std::cout << arr[j] << "\t";    }    std::cout << std::endl;  }}
i see thanks,

just one other question, you know when you have a class or something returning a pointer, you should use a const on the return,

should i also use a const on set functions which use pointers?
eg void setfunc(const float *val);

This topic is closed to new replies.

Advertisement