0

Let assume that I want to get space for an array of x double, x being an integer.

Can someone explain me the difference between

double myArray[x];

and

malloc(x*sizeof(double));

excepted the fact that malloc() returns a void pointer ?

Thank you in advance for your answer.

filaton
  • 2,257
  • 17
  • 27

1 Answers1

1

double myArray[x]; Here memory is

  1. declared on stack
  2. Declared at compile-time, hence faster
  3. Accessible only in the scope of the declaring function,( globally if declared in global scope)
  4. Will be freed if the declaring function returns
  5. generally used when the size of array is known at compile time

myArray = malloc(x*sizeof(double)); Here memory is

  1. declared on heap (except for variable length arrays(C99) which are allocated on stack as pointed by Malina, read more here)
  2. Declared at run-time, hence slower
  3. Accessible wherever the myArray variable is accessible
  4. Will be freed when free(myArray) is called or the program exits
  5. generally used if the size of array is unknown at compile time
Nishant
  • 2,571
  • 1
  • 17
  • 29