开发者

Why i can't watch the expression a[1][1] after declare it by a[n][n] in c++?

开发者 https://www.devze.com 2023-03-06 05:07 出处:网络
my code: #include <iostream> using namespace std; int main() { int n=5; int a[n][n]; a[1][1]=5; return 0;

my code:

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

I got this error when trying to watch the expression a[1][1] in eclipse on line 6:

Failed to execute MI command:开发者_如何学Python -data-evaluate-expression a[1][1] Error message from debugger back end: Cannot perform pointer math on incomplete types, try casting to a known type, or void *.

i guess it's returned from gdb? however, i don't know why i can't watch that value? Isn't "a" is a normal multi-dimensional array?


For some odd reasons this isn't valid C++ unless you make it

const int n = 5;

Otherwise the array size is formally unknown until runtime.


C++ doesn't suppose variable length array (VLA). So your code is not standard conformant code.

It will not compile if you compile it with g++ -pedantic. The array size must be constant expression. But in your code, its not.

So write:

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

Lets try the above code, as its completely Standard conformant code now.


why not better do it a dynamic 2d array? In that case you do not have to make the n 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 the aray as arr[i][j]

To free to 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

精彩评论

暂无评论...
验证码 换一张
取 消