提问者:小点点

函数不改变传递的指针C++


我有我的函数,我正在那里填充targetbubble,但调用这个函数后没有填充,但我知道它是在这个函数中填充的,因为我有那里的输出代码。

bool clickOnBubble(sf::Vector2i & mousePos, std::vector<Bubble *> bubbles, Bubble * targetBubble) {
    targetBubble = bubbles[i];
}

我像这样传递指针

Bubble * targetBubble = NULL;
clickOnBubble(mousePos, bubbles, targetBubble);

为什么它不起作用?谢谢


共2个答案

匿名用户

因为您正在传递指针的副本。要更改指针,您需要如下所示:

void foo(int **ptr) //pointer to pointer
{
    *ptr = new int[10]; //just for example, use RAII in a real world
}

void bar(int *& ptr) //reference to pointer (a bit confusing look)
{
    ptr = new int[10];
}

匿名用户

您正在按值传递指针。

如果要更新指针,请传递指针的引用。

bool clickOnBubble(sf::Vector2i& mousePos, std::vector<Bubble *> bubbles, Bubble *& t)

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(函数|改变|传递|指针|c++)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?