yet another beginner-to-intermediate question. I’m trying to pass a 2-D array to a function in C++. I’m aware that the array can’t be sent directly to the function, so I first created a pointer (names edited but you’ll get the idea):
double input[a][b] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};
Class.calculate (*(input), a, b);
Then I try to use it in said function – but seemingly I’m unaware on how to dereference the pointer to be able to handle the 2-D array again. My code (more or less):
for (int x=0; x<=a; x++){
for (int y=0; y<=b; y++){
tmpInput[x][y]= (*input)[x][y];
}
}
The compiler complains about an error, namely invalid types ‘double[int]’ for array subscript, but I still can’t figure out the problem. My best bet is that I didn’t dereference the 2-D array properly, but the other option is that C++ can’t dereference 2-D arrays directly, instead relying in converting the array to 1-D before sending it. Any ideas?
It’s hard to say for sure without seeing the declaration of
calculate(), but I’d guess it’s an argument type mismatch. You can send your array as adouble*, but not as adouble**– it is an array of doubles (they’re laid out linearly in memory, even if the compiler lets you treat them as a multidimensional array). But it is not an array of pointers to doubles, which is what thedouble**type actually means: Dereference adouble**and you get adouble*.If you know that the second subscript is constant (in your case, 2), you can define
calculate()to expect a N*2 array of doubles:Or, if both dimensions can change, just take a straight
double*and to the pointer math yourself (you’ll probably have to cast your array to adouble*when calling this, but it’ll work):Hope this helps!