gpt4 book ai didi

c++ - 如果我删除指向节点的指针数组,节点本身会被删除吗?

转载 作者:行者123 更新时间:2023-11-28 04:42:28 25 4
gpt4 key购买 nike

假设我创建了一个指向节点的指针数组,每个节点包含一个汽车对象成员变量,以便按 mpg 的降序打印它们。一旦我按照 MPG 的降序对数组进行排序并打印出最终结果,我想删除我创建的指针数组。

删除最后的数组是否也会删除单链表中的节点?

cout << "\nCARS RANKED BY MPG\n-------------\n";

int capacity = count; //number of nodes in the list
Node **a = new Node*[capacity];
int numOfElem = 0;

Node *currentCar = first; //create a pointer to the first node in the list

while (numOfElem < count)
{
a[numOfElem++] = currentCar; //populate the array of pointers
currentCar = currentCar->getLink();
}

//Do something....

delete[] a; //delete array of pointers
a = nullptr;

最佳答案

不,你只是在释放 a 本身指向的内存。该内存的内容不会以任何方式处理。

如果你想自动“删除”对象,使用智能指针,或者更好的是 std::vector 对象(不是指向对象的指针)。

关于c++ - 如果我删除指向节点的指针数组,节点本身会被删除吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49933382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com