So my code is this :
int a, b;
printf("Give dimensions\n");
scanf("%d %d", &a, &b);
double array1[a][b];
printf("Give values\n");
int i, j;
for(i=0; i<a; i++)
{
for(j=0; j<b; j++)
{
scanf("%lf", &array1[i][j]);
}
}
My problem is, i am told this is a wrong way to allocate memory and that i should use malloc. I was supposed to create a dynamic array using user's dimensions.
Edit: rest of the program:
double sum=0;
for(i=0; i<a; i++)
{
for(j=0; j<b; j++)
{
sum = sum + array1[i][j];
}
printf("Line %d: sum = %lf\n", i+1, sum);
sum=0;
}
Depends on how you define "correct". This is legal C since C99.
The problem however, is that if a
and b
are too large, the array will overflow the call stack. If this is a likely scenario, you should prefer malloc
. The call stack is usually allocated to be fairly small compared to the heap. So that's probably the source of the advice.
Note that you can still enjoy the array subscript notation with dynamically allocated arrays:
double (*array)[b] = malloc(sizeof(double[a][b]));
The array is in one continuous block, and the VLA pointer will result in a[i][j]
referencing the correct element.
No, this is perfectly correct and valid way, as long as you are using a compiler version / environment which supports Variable-length array.
This was a mandatory feature as on C99
but again made optional on C11
.
The major differences between using VLA and a "pointer-and-memory-allocator functions-combination" are
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With