0

Why do we use pointers and malloc/calloc when we use dynamic sized arrays instead of giving the size of the array as a variable?

int *array = (int*)malloc(sizeof(int) * (n));
for (int i = 0; i < n; i++ ) array[i] = 1;

// What are their differences?

int array[n];
for (int i = 0; i < n; i++ ) array[i] = 1;
keser
  • 2,472
  • 1
  • 12
  • 38
  • 1
    Also in C we do not cast the result of `malloc`, because doing so has only drawbacks and no advantage. https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Pascal Cuoq Oct 24 '18 at 16:53
  • Why? Where do local variables get allocated? What limits are imposed on the size of those variables? What lifetime to locally allocated variables have? – tadman Oct 24 '18 at 16:54
  • One important difference (apart from the fact that one is an array and the other is a pointer) is that the memory allocated by `malloc` needs to be `free`d to avoid a memory leak. – Ian Abbott Oct 24 '18 at 16:59

0 Answers0