gpt4 book ai didi

c++ - 在 C++ 中为指针赋值

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:36:15 43 4
gpt4 key购买 nike

这是我使用的一段代码:

void Move::AddToMovesList(Location* &list, int row, int col) {
// If the list is empty, create the first item
if (list == NULL)
list = new Location(row, col);
// List exists, so append
else
list->Add(row, col);
}

如果 listNULL,一个新的 Location 应该被创建并且指针 list 应该指向那个新位置。这是我期望从这段代码中得到的行为,但是就在 gdb 退出这个函数之前,我注意到 list 仍然是 NULL。我在这里做错了什么?

我在 Location* &list 中使用了 & 符号来确保我可以永久(相对于本地)更改提供的指针。

最佳答案

我们不要在这里重新发明轮子... Know your libraries.

如果您使用 STL 列表容器(或任何其他容器),则无需为空指针而烦恼。

关于c++ - 在 C++ 中为指针赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3841895/

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