C++:整数数组[a][b][c] = {0};没有将所有值都设置为 0。该指令是错误的还是我的输出函数有问题?

C++: int array[a][b][c] = {0}; not setting all values to 0. Is that instruction wrong or is there something wrong with my output function?

我初始化矩阵并在 int main() 中像这样调用输出

int array[a][b][c] = {0};
OMat3(a,b,c,(int*)array);

这是输出函数

void OMat3(int rig,int col,int pro,int *mat){
    for (int a=0;a<rig;a++){
        printf("\n%da Materia:\n",a+1);
        for (int b=0;b<col;b++){
            printf("\n\t%d Giorno: ",b+1);
            for (int c=0;c<pro;c++){
                printf("%d  ",mat[a*col*pro+b*pro+c]);
            }
        }
    }
}

问题是在输出中我不只得到 0(大部分是 0,但有时会有疯狂的高值)。

是我初始化为0错误还是我的输出函数有问题?

示例程序

void OMat3(int rig,int col,int pro,int *mat){
    for (int a=0;a<rig;a++){
        printf("\nRow %d:\n",a+1);
        for (int b=0;b<col;b++){
            printf("\n\tColumn %d: ",b+1);
            for (int c=0;c<pro;c++){
                printf("%d  ",mat[a*col*pro+b*pro+c]);
            }
        }
    }
}
int main(){
    int a,b,c;
    printf("Insert the array's dimensions: ");
    scanf("%d %d %d",&a,&b,&c);
    int array[a][b][c] = {0};
    OMat3(a,b,c,(int*)array);
}

如果这很重要,我正在使用 TDM-GCC 4.9.2 64 位版本

使用 array[a][b][c]={} 按预期工作并将所有值初始化为 0

感谢@AndyG 发现了这一点。

首先,这不是合法的 C++ 语法:

int a,b,c;
//...
int array[a][b][c] = {0};

问题是 C++ 不允许声明数组时将变量用作项数。所以数组声明中不能使用abc。数组的大小必须使用 编译时 表达式声明,而不是在运行时确定的值。

您使用的是GCC提供的扩展,即Variable Length Arrays。如果您使用 g++-Wall -pedantic 标志编译您的代码,您将得到我所说的错误。

缓解这种情况的方法是使用 std::vector<int>

#include <vector>
//..
int a, b, c;
//..assume a, b, and c have values
std::vector<int> array(a*b*c);
//... call the function
OMat3(a, b, c, array.data());