0

I was writing a program and suddenly came through a doubt. There are two ways i am assigning static array.

int main ()
{ 
   int a[10];
}
int main()
{
    int N;
    cin >> N;  //assume i input N as 10
    int a[N];
}

How will memory allocation differ in both cases? Will be assigned during runtime in second case?

Prannoy Mittal
  • 1,525
  • 5
  • 21
  • 32

2 Answers2

2

The second way is not allowed. The first way will create memory on the stack. As soon as main() exits it will be de-allocated. If you want dynamic allocation best way is to use new:

int* = new int[N];

But then this way you would have to delete it, in the end. If you're OK with using STL then just go with std::vector:

std::vector<int> a;
santahopar
  • 2,933
  • 2
  • 29
  • 50
0

The second one is compiled. But it is wrong. Standard C/C++ does not allow it.

Sujith Gunawardhane
  • 1,251
  • 1
  • 10
  • 24