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

标签 c++ function multidimensional-array initialization

我初始化矩阵并在 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 位版本

最佳答案

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

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

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

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

缓解这种情况的方法是使用 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());

关于C++:整数数组[a][b][c] = {0};没有将所有值都设置为 0。该指令是错误的还是我的输出函数有问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34362531/

相关文章:

c++ - 如何防止 libwebsockets 客户端超时

php - 请解释这个 PHP 函数定义

javascript - 字符串中的交替大写

php - 在 PHP 中对多数组进行排序

c++ - 使用 a 升和 b 升(算法)测量 c 升

c++ - 使用 Visual Studio 2008 从 x86 编译 x64 dll

C++成员数组未初始化

php - Yii 在创建数据库列之前检查它是否存在

c - C 中的二维结构数组? (或许)

php - 通过使用元素分组并通过另一个过滤来复制 CSV 文件