可能无法初始化可变大小的对象

时间:2013-11-07 11:31:10

标签: 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')

2 个答案:

答案 0 :(得分:2)

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

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

#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;
}

答案 1 :(得分:1)

在C99中,无法初始化可变大小的数组,为什么?

因为在编译时,编译器不知道数组的确切大小,所以你不能初始化它。

n将在运行时进行评估,然后您的数组将在堆栈帧上分配。