Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Length vs Malloc-ed arrays

Tags:

arrays

c

According to c99 standard, we can write the following code and it's totally legal

int x;
scanf("%d",&x);
int ar[x];

My question is, if I can allocate an array like this, why would I ever need malloc to allocate variable size arrays again?

Also, could you please explain how does the variable length arrays allocation happens? Deep inside, does it call malloc to allocate the array or what?

like image 703
Fingolfin Avatar asked Jul 08 '11 19:07

Fingolfin


1 Answers

Two reasons spring to my mind:

  1. Arrays that live beyond this stack frame.
  2. Arrays that are bigger than the stack.
like image 120
David Heffernan Avatar answered Oct 25 '22 12:10

David Heffernan