为什么我会得到"cannot allocate an array of constant size 0"?

Why do I get "cannot allocate an array of constant size 0"?

本文关键字:of array constant size an allocate cannot 为什么      更新时间:2023-10-16

我正在为学校做扫雷程序,但我的代码上一直出现这个错误

无法分配大小为0的数组

我不知道为什么会发生这种事;我没有分配大小--我将其设置为0。另一个问题是,如何通过char读取输入的char,以便将其保存在数组中?

正如您在下面看到的,我使用的是输入和输出。我得到了我的输入和输出,所以你们可以看到我在这个程序中使用了什么。我想通过char读取char,这样我就可以保存数组上的所有映射。

我正在使用MSVC++2010。

freopen("input.txt","rt",stdin);
//4 4
//*...
//....
//.*..
//....
//3 5
//**...
//.....
//.*...
//0 0

freopen("output.txt","wt",stdout);
/*Field #1:
*100
2210
1*10
1110
Field #2:
**100
33200
1*100*/
int n=-1;
int m=-1;
int cont =0;
while(n!=0 && m!=0)
{
    scanf("%d %d",&n,&m);
    int VMatriz[n][m]={0};
    int Mapa[n][m]={0};

    if (n==0 && m==0)
        break;
    cont++;
    printf("Field #%d",cont);

    for (int i=0;i<n;i++)
    {   printf("/n");
        for (int j=0;j<m;j++)
        {
            scanf("%d ",&Mapa[i][j]);
            if (Mapa[i][j]=='*')
                {
                    if (j-1>=0)
                        VMatriz[i][j-1]++;
                    if (j+1<m)
                        VMatriz[i][j+1]++;
                    if (i-1>=0)
                        VMatriz[i-1][j]++;
                    if (i+1<m)
                        VMatriz[i+1][j]++;
                    if (j-1>=0 && i-1>0)
                        VMatriz[i-1][j-1]++;
                    if (j-1>=0 && i+1<m)
                        VMatriz[i+1][j-1]++;
                    if (j+1<m && i-1>0)
                        VMatriz[i-1][j+1]++;
                    if (j+1<m && i+1<m)
                        VMatriz[i+1][j+1]++;
                    VMatriz[i][j]='*';
                printf("%d",VMatriz[i][j]);

                }
        }   
    }
    printf("/n");

}
return 0;

}

int VMatriz[n][m]={0};

这是违法的。就像这个更简单的版本一样;

int n = 10;
int x[n]; // C2057

然而。。。

int x[10]; // ok!

您真正关心的错误是这个错误,而不是"无法分配常量大小为0的数组"的错误。

错误C2057:应为常量表达式

无法在C++中分配具有自动存储持续时间的未知大小的数组。如果您想要一个可变大小的数组,那么您需要动态分配它(或者,更好的是,只需使用vector)。

请注意,有一个gcc扩展允许这样做,但在VS中没有(它不是标准C++。它是为C++11提交的,但最终被拒绝了。)