C++ 为什么我能';在c+中用a[n][n]声明后,不要看表达式a[1][1+;?

C++ 为什么我能';在c+中用a[n][n]声明后,不要看表达式a[1][1+;?,c++,eclipse,gdb,C++,Eclipse,Gdb,我的代码: #include <iostream> using namespace std; int main() { int n=5; int a[n][n]; a[1][1]=5; return 0; } #包括 使用名称空间std; int main(){ int n=5; INTA[n][n]; a[1][1]=5; 返回0; } 我在第6行尝试查看eclipse中的表达式a[1][1]时遇到此错误: 无法执行MI命令: -来自调试器后端的

我的代码:

#include <iostream>
using namespace std;
int main() {
    int n=5;
    int a[n][n];
    a[1][1]=5;
    return 0;
}
#包括
使用名称空间std;
int main(){
int n=5;
INTA[n][n];
a[1][1]=5;
返回0;
}
我在第6行尝试查看eclipse中的表达式a[1][1]时遇到此错误:

无法执行MI命令: -来自调试器后端的数据计算表达式[1][1]错误消息: 无法在上执行指针数学运算 类型不完整,请尝试强制转换为 已知类型,或void*


我想是从gdb寄回来的吧?然而,我不知道为什么我不能看到那个值?“A”不是一个普通的多维数组吗?< /P> < P>由于一些奇怪的原因,这不是有效的C++,除非你把它变成< /P>
const int n = 5;

否则,直到运行时,数组大小才正式确定。

C++不假设可变长度数组(VLA)。因此,您的代码不是符合标准的代码

如果使用
g++-pedantic
编译它,它将不会编译。数组大小必须是常量表达式。但在你的代码中,它不是

所以写下:

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

让我们试试上面的代码,因为它现在是完全标准的一致代码。

为什么不把它作为一个动态2d数组来做呢?在这种情况下,不必使n为常量,您可以动态地确定大小

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.
}

“一些奇怪的原因”是可变长度数组不是C++的一部分。@ AvaKar——奇怪的部分是每个人都可以看到N总是5。它在矩阵上方的一行上这样写,而n永远不会改变(在这段代码中)。实际上程序运行得很好@我只是不能调试[1][1],但我仍然可以使用程序代码设置它的值/获取它的值。。。这是否意味着在运行时创建了一个“?”——G+++编译器有一个扩展,它接受C++的代码。它在C99中有效,因此编译器知道如何处理它。也许调试器没有?@博佩森:<代码>奇怪的部分是,每个人都可以看到N总是5 :在正确的C++语法上有一个区别:“在语法验证之后,编译器优化后,你只能初始化一个数组大小,并带有一个<代码> const < /COD>值”。“哦,它是5,目前没有人更改它,所以我想应该可以内联该值”)。
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)