gpt4 book ai didi

C++:链表和指针乐趣

转载 作者:搜寻专家 更新时间:2023-10-31 00:17:13 24 4
gpt4 key购买 nike

这里关于指针的使用有一件事我不明白 Cell *curr = head; 这里取 head 的地址以及它是做什么用的?

Cell *ConvertToListIter(Vector<int>& vector)
{
Cell *head = new Cell;
head->next = NULL;
head->value = vector[0];
Cell *curr = head;

for (int i = 1; i < vector.size(); i++) {
Cell *newCell = new Cell;
newCell->next = NULL;
newCell->value = vector[i];
curr->next = newCell;
newCell = curr;
}

return head;
}

最佳答案

Cell *curr = head; 不采用 head地址 -- 它采用 head 恰好是一个指针:

Cell *head = new Cell;

因此,在 Cell *curr = head; 执行后,currhead 都指向同一事物。

根据您的评论

编辑:

So if i then delete one of them it will affect both? they point to the same address in memory, not two copies of the same value yes?

没错。这两个指针指向内存中的单个对象。该对象只需删除一次。事实上,尝试删除两次会导致未定义的行为,而且通常会导致程序崩溃。

关于C++:链表和指针乐趣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13996420/

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