简体   繁体   中英

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?

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM