函数不会更改传递的指针C++

Function does not change passed pointer C++

本文关键字:指针 C++ 函数      更新时间:2023-10-16

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

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

我正在像这个一样传递指针

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

为什么它不起作用?

因为您正在传递指针的副本。要更改指针,您需要这样的东西:

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)

如果您编写

int b = 0;
foo(b);
int foo(int a)
{
  a = 1;
}

您不能更改"b",因为a是b 的副本

如果你想更改b,你需要通过b 的地址

int b = 0;
foo(&b);
int foo(int *a)
{
  *a = 1;
}

指针也是如此:

int* b = 0;
foo(b);
int foo(int* a)
{
  a = malloc(10);  // here you are just changing 
                   // what the copy of b is pointing to, 
                   // not what b is pointing to
}

以便更改b指向的位置以传递地址:

int* b = 0;
foo(&b);
int foo(int** a)
{
  *a = 1;  // here you changing what b is pointing to
}

hth

除非通过(非常量)引用或作为双指针传递,否则无法更改指针。传递值会生成对象的副本,对对象的任何更改都是对副本而不是对象进行的。如果按值传递,则可以更改指针指向的对象,但不能更改指针本身。

阅读一下这个问题,以帮助更详细地理解C++中何时通过引用传递和何时通过指针传递的区别?