Reputation: 55
So this section of code generates a huge amount of errors but it works when I have InputM[3][3] = blah
Why would this be. For reference, code:
int n = 3;
printf("%ld\n", n);
double InputM[n][n] = { { 2, 0, 1 }, { 3, 1, 2 }, { 5, 2, 5} };
Generates:
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')
Upvotes: 1
Views: 3284
Reputation: 646
Compile-time, you compiler does not know how many elements are in your matrix. In C, you can dynamically allocate memory using malloc.
You could use a define to create a constant value:
#define N 3
int main()
{
double InputM[N][N] = { { 2, 0, 1 }, { 3, 1, 2 }, { 5, 2, 5} };
}
Or 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;
}
Upvotes: 3
Reputation: 1052
In C99, variable-sized array can't be initialized, why ?
Because at the compile time, the compiler doesn't know the exact size of array, so you cannot initialize it.
n will be evaluated at runtime, then your array will be allocated on the stack-frame.
Upvotes: 1