Why can't I look at the expression a [1] [1] after declaring it with [n] [n] in C ++?

my code is:

#include <iostream>
using namespace std;
int main() {
    int n=5;
    int a[n][n];
    a[1][1]=5;
    return 0;
}

I got this error while trying to look at the expression a [1] [1] in eclipse on line 6:

The MI command failed to execute: -data-evaluation-expression a [1] [1] Error message from the end of the debugger: Cannot execute the math on pointer to incomplete types, try pouring a known type or void *.

I assume he came back from gdb? however, I do not know why I cannot look at this value? Isn't "a" a normal multidimensional array?

+3
source share
3 answers

For some odd reasons, this is unacceptable in C ++ unless you have done so.

const int n = 5;

Otherwise, the size of the array is formally unknown before execution.

+6

++ (VLA). , .

, g++ -pedantic. . .

, :

 const int n=5; //now this becomes constant!
 int a[n][n]; //the size should be constant expression.

.

+4

why not make it a dynamic 2d array? In this case, you do not need to make n a constant, and you can determine the size dynamically.

int **arr, n;

arr = new int * [n]; // allocate the 1st dimension. each location will hole one array
for (i=0; i<n; i++)
{
  arr[i] = new int [n]; // allocate the 2nd dimension of one single n element array
                        // and assign it to the above allocated locations.
}

Now you can access aray as arr[i][j]

To free the reverse

for (i=0; i<n; i++)
{
  delete [] arr[i]; // first delete all the 2nd dimenstion (arr[i])
}
delete [] arr; // then delete the location arays which held the address of the above (arr)
0
source

All Articles