If I create a file:
test.cpp:
void f(double **a) {
}
int main() {
double var[4][2];
f(var);
}
And then run: g++ test.cpp -o test
I get
test.cpp: In function `int main()':
test.cpp:8: error: cannot convert `double (*)[2]' to `double**' for argument `1'
to `void f(double**)'
Why is that I can't do this?
Isn't double var[4][2] is the same as doing double **var and then allocating the memory?
C++ strings: [] vs. *
Look at the Excursion: Multi Dimensional Arrays which describes how you pass multi dimensional arrays to functions as arguments. Basicially you want to change your code into this:
// same as void f(double (*a)[2]) {
void f(double a[][2]) {
}
int main() {
// note. this is not a pointer to a pointer,
// but an array of arrays (4 arrays of type double[2])
double var[4][2];
// trying to pass it by value will pass a pointer to its
// first element
f(var);
}
All but the last dimensions have to be known to the called function. Otherwise indexing the array, the compiler would not be able to calculate the correct distance to values into your array (a[1] is sizeof(double[2])
bytes away from a[0]).
You seem to want to be able to accept the array without knowing the size of the dimensions. You can use templates for this:
template<std::size_t N>
void f(double a[][N]) {
// N == 2 for us
}
int main() {
double var[4][2];
f(var);
}
The compiler will make a copy of (instantiate) that template for each value of N used with the function, auto-deducing the right N.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With