c++ memory allocated at compile time

时间:2015-06-15 14:26:37

标签: c++ memory-management stack static-allocation

I read that while dynamic memory is allocated on the heap during runtime, static memory is allocated on the stack during compile time since the compiler knows how much memory has to be allocated at compile time.

Consider the following code:

int n;
cin>>n;
int a[n];

How does the compiler possibly know how much memory to allocate for a[] at compile time if its actual size is read during the run only?

1 个答案:

答案 0 :(得分:4)

You won't be able to compile that, for the exact reason you specified. C++ needs to have a fixed number in there in order for compilation to be performed. If you want to do that, you have to use dynamic allocation.