简体   繁体   中英

C++ 2D array to function - Why second index cannot be variable

Take this code.

using namespace std;
int x = 10;

void test(int arr[][x]);

int main() {
   int mainArr[4][x];
   testFunc(mainArr);
}

void test(int arr[][x]) {
     ...
}

Now, this code doesn't work. And I get an error message of note: candidate function not viable: no known conversion from 'int [4][10]' to 'int (*)[x]' for 1st argument void test(int arr[][x]);' . Now, I know that it would work if I replaced every time I saw and x with the number 10. That's not what I am asking though. I am asking why c++ will not allow we to put a variable into the function definition? I feel that I am not understanding the way that c++ deals with global variables, 2d arrays and/or function definitions and would appreciate if someone could fill me in on what I am not understanding because I feel that the code that I have written above should be able to compile. Thanks.

When the array is passed to the function it is just passed a pointer to the beginning of the array. If the function doesn't know the size of all the lower order dimensions, then it won't be able to calculate addresses for items in the array.

If for example you had a reference in your function to arr[3][4] then if it knows the lower dimension is 10, it can do the calculation 3*10 + 4 to calculate the location of that item.

Other types have additional data that comes with them and that can contain information like the size of each dimension, but that isn't the case for a C/C++ array.

If you are wondering why it can't just use the value from the global, that is because it needs to know the value at compile time. If you change the declaration to:

const int x = 10;

Then it will be fine with your code since it knows that x is always 10, so it can take that into account at compile time.

C-style just don't allow that in C++. C-style arrays must have constant dimension. Use of them is discouraged anyway. They are mainly in the language as a historical hangover from C.

The name in C++ for an array whose size is not known at compile-time is vector . Your code could look like:

int x = 10;

void testFunc(vector<vector<int>> &x);

int main() 
{
    vector<vector<int>> mainArr{ 4, vector<int>{x} };
    testFunc(mainArr);
}

If the 4 does not need to change, you could use array<vector<int>, 4> instead, or make the 4 a template parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM