我读到了关于C ++动态内存分配的内容。这是我的代码:
#include <iostream>
using namespace std;
int main()
{
int t;
cin>>t;
int a[t];
return 0;
}
以上和以下之间有什么区别:
int* a=new(nothrow) int[t];
答案 0 :(得分:2)
使用动态分配:
回答您的具体问题:int a[t];
无效C ++,因为数组大小必须是常量。有些编译器允许这样的可变长度数组作为扩展,从C借用;但你不应该使用它们,除非你不介意被绑定到那个编译器。
所以你想要那里的动态分配,或者由RAII管理的简单方法:
std::vector<int> a(t);
// use it, let it clean itself up when it goes out of scope
或艰难的方式,由杂耍指针管理,并希望你不要放弃它们:
int* a=new int[t];
// use it, hope nothing throws an exception or otherwise leaves the scope
delete [] a; // don't forget to delete it
答案 1 :(得分:0)
你的第一个例子是与C99兼容的数组分配,这些分配发生在堆栈上,其生命周期与其他局部变量类似。
分配示例是一个典型的C ++动态内存分配,它从堆中发生,其生命周期一直延伸到delete a[]
- 没有此代码,内存被“泄露”。生命之一发生在变量被delete
破坏的情况下,并且可能在当前本地范围结束后发生。