Prannoy Mittal
Prannoy Mittal

Reputation: 1575

Simple array memory allocation with size dynamic allocated and predetermined size

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?

Upvotes: 0

Views: 104

Answers (2)

tsragravorogh
tsragravorogh

Reputation: 3173

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;

Upvotes: 2

Sujith Gunawardhane
Sujith Gunawardhane

Reputation: 1311

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

Upvotes: 0

Related Questions