I have a function which I want to take, as a parameter, a 2D array of variable size.
So far I have this:
void myFunction(double** myArray){
myArray[x][y] = 5;
etc...
}
And I have declared an array elsewhere in my code:
double anArray[10][10];
However, calling myFunction(anArray)
gives me an error.
I do not want to copy the array when I pass it in. Any changes made in myFunction
should alter the state of anArray
. If I understand correctly, I only want to pass in as an argument a pointer to a 2D array. The function needs to accept arrays of different sizes also. So for example, [10][10]
and [5][5]
. How can I do this?
A modification to shengy's first suggestion, you can use templates to make the function accept a multi-dimensional array variable (instead of storing an array of pointers that have to be managed and deleted):
The print statements are there to show that the arrays are getting passed by reference (by displaying the variables' addresses)
You can create a function template like this:
Then you have both dimension sizes via R and C. A different function will be created for each array size, so if your function is large and you call it with a variety of different array sizes, this may be costly. You could use it as a wrapper over a function like this though:
It treats the array as one dimensional, and uses arithmetic to figure out the offsets of the indexes. In this case, you would define the template like this:
Surprised that no one mentioned this yet, but you can simply template on anything 2D supporting [][] semantics.
It works with any 2D "array-like" datastructure, such as
std::vector<std::vector<T>>
, or a user defined type to maximize code reuse.anArray[10][10]
is not a pointer to a pointer, it is a contiguous chunk of memory suitable for storing 100 values of type double, which compiler knows how to address because you specified the dimensions. You need to pass it to a function as an array. You can omit the size of the initial dimension, as follows:However, this will not let you pass arrays with the last dimension other than ten.
The best solution in C++ is to use
std::vector<std::vector<double> >
: it is nearly as efficient, and significantly more convenient.One important thing for passing multidimensional arrays is:
First array dimension
need not be specified.Second(any any further)dimension
must be specified.1.When only second dimension is available globally (either as a macro or as a global constant)
2.Using a single pointer: In this method,we must typecast the 2D array when passing to function.
Single dimensional array decays to a pointer pointer pointing to the first element in the array. While a 2D array decays to a pointer pointing to first row. So, the function prototype should be -
I would prefer
std::vector
over raw arrays.