1

したがって、コードのこのセクションは大量のエラーを生成しますが、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')
4

2 に答える 2

3

コンパイル時に、コンパイラは行列に含まれる要素の数を知りません。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;
}
于 2013-11-07T11:33:22.667 に答える