What is the correct way to allocate memory for an array depending on a command line parameter?

When writing a program where I ask the user to enter the number N which I should use to allocate memory for an array int

, what is the correct way to handle this:

First approach:

int main() {
  int array[],n;
  scanf("%d\n",&n);
  array = malloc(n * sizeof(int));
}

      

or second approach:

int main() {
  int n;
  scanf("%d\n",&n);
  int array[n];
}

      

+3


source to share


4 answers


Either one will work (although the first case must be changed from int array[]

to int *array

); the difference depends on where the array is stored.



In the first case, the array will be stored on the heap, and in the second case, it will (most likely) be stored on the stack. When stored on a stack, the maximum size of the array will be much more limited depending on the limit on the stack size. However, if stored on the heap, it can be much larger.

+4


source


Your second approach is called Variable Length Array (VLA) and is only supported since c99. This means that if you intend to make your code compatible with older compilers (or for older people to read and understand them ..), you may have to revert to the first option, which is more standard. Note that dynamically allocating data requires proper maintenance, with the most important part of it being freeing it up when you're done (which you don't in your program).



+1


source


Assuming you used int *array;

instead int array[];

(the first one won't compile).

Always use the first approach unless you know the array size will be very small and you have a deep knowledge of the platforms you will be working on. The question naturally arises, how small is small enough?

The main problem with the second approach is that there is no portable way to check if a VLA (Varible Length Array) has been distributed. The advantage is that you don't need to manage memory, but this is hardly an "advantage" given the risk of undefined behavior on memory failure.

It was introduced in C99 and made optional in C11 . This suggests that the committee did not find it very useful. Also, C11 compilers may not support it and you need to do an extra check if your compiler supports it or not by checking if it was __STDC_NO_VLA__

defined.

Automatic allocation of storage for an array as small int my_arr[10];

may fail. This is an extreme and unrealistic example in modern operating systems, but possible in theory. Therefore, I suggest avoiding VLA in any serious projects.

+1


source


You said you want the COMMAND LINE option:

  int main (int argc, char **argv)
  {
     int *array ;
     int count ;
     if (argc < 2)
       return 1 ;
     count = atoi (argv[1]) ;
     array = malloc (sizeof(int)*count) ;

     . . .  . . 

     free (array) ;
     return 0 ;
  }

      

0


source







All Articles