In C what is the difference between a normal array and an array created with malloc? [duplicate]

StackOverflow https://stackoverflow.com/questions/23566210

  •  19-07-2023
  •  | 
  •  

Question

Let's say I declare an array by doing this:

int array[] = {1, 2, 3, 4};

By what I understand, you can also create the same array using pointers and malloc:

int* array = malloc(sizeof(int) * 4);  
*(array) = 1;
*(array + 1) = 2;
*(array + 2) = 3;
*(array + 3) = 4;

What is the difference between the two ways? Is one necessarily better than the other?

Was it helpful?

Solution

The first one resides in the current function's call stack. The second one resides in the heap.

The first one goes out of scope when the function returns, the second persists until free() is called on the address.

More differences, but I defer to the duplicate found by lethal-guitar instead of adding to my answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top