c - 可变大小的对象可能未被初始化

标签 c arrays initialization

所以这部分代码会产生大量错误,但当我有 InputM[3][3] = blah 时它会起作用

为什么会这样。供引用,代码:

int n = 3;
printf("%ld\n", n);
double InputM[n][n] = { { 2, 0, 1 }, { 3, 1, 2 }, { 5, 2, 5} };

生成:

prog3.c: In function 'main':
prog3.c:47: error: variable-sized object may not be initialized
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM[0]')
prog3.c:47: warning: excess elements in array initializer
prog3.c:47: warning: (near initialization for 'InputM')

最佳答案

编译时,编译器不知道矩阵中有多少元素。在 C 中,您可以使用 malloc 动态分配内存。

您可以使用定义来创建常量值:

#define N 3

int main()
{
    double InputM[N][N] = { { 2, 0, 1 }, { 3, 1, 2 }, { 5, 2, 5} };
}

或者 malloc:

int main()
{
    int n = 3;
    int idx;
    int row;
    int col;

    double **inputM;
    inputM = malloc(n * sizeof(double *));
    for (idx = 0; idx != n; ++idx)
    {
        inputM[idx] = malloc(n * sizeof(double));
    }

    // initialise all entries on 0
    for (row = 0; row != n; ++row)
    {
        for (row = 0; row != n; ++row)
        {
            inputM[row][col] = 0;
        }
    }

    // add some entries
    inputM[0][0] = 2;
    inputM[1][1] = 1;
    inputM[2][0] = 5;
}

关于c - 可变大小的对象可能未被初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19834800/

相关文章:

c - 字符串文件到C中的数组

c++ - 在大括号初始化结束时与额外的 ","有什么关系吗?

使用递归将一个基数转换为另一个基数

c - 使用 free() 释放指针后使用指针

arrays - 如何将 Byte[] 插入 SQL Server VARBINARY 列

java - 在 Java 中构建通用初始化函数

java - 导入扫描仪时必须声明一个命名包

objective-c - : Use of undeclared identifier '_cmd' 的解决方法

c - 链接列表问题 - 当用户输入 'N 停止添加更多元素时,为什么会添加 0 作为元素到我的列表中?

javascript - ruby 是否有相当于 javascript 的 Array.prototype.every 方法?