开发者

Dynamic memory allocation in C++ require the new operator new?

开发者 https://www.devze.com 2023-03-23 12:43 出处:网络
int d; cin >> d; int asdf[d]; Is this considered dynamic memory allocation? According to http://www.cplusplus.com/doc/tutorial/dynamic/, it seems like I shouldn\'t even be able to compile this
int d;
cin >> d;
int asdf[d];

Is this considered dynamic memory allocation? According to http://www.cplusplus.com/doc/tutorial/dynamic/, it seems like I shouldn't even be able to compile this, because arrays without using the new operator can only be declared with constant size, maybe I read it wrong. (开发者_如何学CI'm using CodeBlocks with GNU CCC compiler)

What is the difference between that and

int d;
int *asdf;
cin >> d;
asdf = new int[d];

Is the only difference that array created using new lives until it is deleted, whereas the first array becomes freed as soon as you leave the scope?


int x[n]; is a variable-length array (VLA), which has automatic storage duration (i.e. "on the stack"). It is not valid in C89 or C++98/03, but it was introduced in C99 and is commonly available as an extension, e.g. in GCC.

The functionality can also be mimicked on some platforms with the non-standard alloca() function, which was used before VLAs became common.


The memory allocated with the first method is from the stack that is allocated to the application. when you use new the memory is allocated from the heap, heap can provide enough memory way much than you can get from stack. But to use new your variable must be pointer of the same type as your array would be. pointer variable holds the address of the first memory cell. int * a = new int[x]; will hold x memory cells, and will be released if you specifically delete the pointer while the programme is still running.

0

精彩评论

暂无评论...
验证码 换一张
取 消