Cam*_*ler 2 c++ free pointers memory-management heap-memory
我很疑惑怎么都new int和new int[n]返回int*。为什么后者不返回一个int**?
以下是一些上下文:请参阅dataGoodrich、Tamassia 和 Mount 的第二版中的一个片段中的以下变量。C++ 教科书中的数据结构和算法:
class Vect {
public:
Vect(int n);
~Vect();
// ... other public members omitted
private:
int* data;
int size;
};
Vect::Vect(int n) {
size = n;
data = new int[n];
}
Vect::~Vect() {
delete [] data;
}
Run Code Online (Sandbox Code Playgroud)
(答案包含为了解释而进行的简化)
在 C 中,
int**如果我没记错的话,指向 int 数组的指针的类型是 。
你误会了。在 C 中,它也是int*.
当您声明: 时int foo[] = { 1, 2, 3 },数组的名称 ( foo) 可以被视为指向其第一个元素 ( 1) 的指针。指向的int是int*。
另外,为什么我们调用
delete[]而不是delete, 来删除int*(数据)?
delete删除单个对象。delete []删除动态数组。