Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i make a dynamic array this way?

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;
}
like image 506
vailanter Avatar asked Dec 02 '22 13:12

vailanter


2 Answers

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.

like image 89
StoryTeller - Unslander Monica Avatar answered Dec 19 '22 00:12

StoryTeller - Unslander Monica


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

  • VLAs are block scoped. a VLA does not live outside the scope, so it cannot be returned from a function and be used in the caller, unlike the pointer-and-malloc approach.
  • Usually VLAs are allocated in stack for all major implemenataions, so that is size limited.
like image 34
Sourav Ghosh Avatar answered Dec 18 '22 23:12

Sourav Ghosh