C++, How to make a function accept a 2 dimensional array of any size?
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.
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
myFunction( float *var[] );
~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 << '\t' ;<br> }<br><br> cout << '\n' ;<br> }<br>}<br><br></pre></div><!–ENDSCRIPT–>
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.
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...
Once they've been completely initialized, you can access a and b as 2d arrays.
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.
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; }}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement