C++ 中的动态内存分配需要新的运算符 new 吗?
int d;
cin >> d;
int asdf[d];
这是否被认为是动态内存分配?根据 http://www.cplusplus.com/doc/tutorial/dynamic/ ,看来我什至不应该能够编译这个,因为不使用 new 运算符的数组只能声明为常量大小,也许我读错了。 (我正在使用 CodeBlocks 和 GNU CCC 编译器)
这和
int d;
int *asdf;
cin >> d;
asdf = new int[d];
使用新生命创建的数组直到被删除的唯一区别是什么,而一旦离开作用域,第一个数组就会被释放?
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. (I'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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
int x[n];
是一个变长数组 (VLA),它具有自动存储持续时间(即“在堆栈上”)。它在 C89 或 C++98/03 中无效,但在 C99 中引入,并且通常可作为扩展使用,例如在 GCC 中。还可以在某些平台上使用非标准
alloca()
函数来模仿该功能,该函数在 VLA 变得普遍之前就已使用。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.第一种方法分配的内存来自分配给应用程序的堆栈。当您使用 new 时,内存是从堆中分配的,堆可以提供比从堆栈中获得的内存更多的足够内存。但要使用 new,变量必须是与数组类型相同的指针。指针变量保存第一个存储单元的地址。 int * a = 新 int[x];将保存x个内存单元,如果您在程序仍在运行时专门删除指针,则该内存单元将被释放。
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.