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

c0n*_*rol 41 c++ pointers function

我有我的功能,我在targetBubble那里填充,但它在调用此函数后没有填充,但我知道它已填充此函数,因为我有输出代码.

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

我正在传递这样的指针

Bubble * targetBubble = NULL;
clickOnBubble(mousePos, bubbles, targetBubble);
Run Code Online (Sandbox Code Playgroud)

为什么它不起作用?谢谢

And*_*rew 86

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

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

要么

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


Dan*_*nas 25

您正在按值传递指针.

如果要更新指针,请传递对指针引用.

bool clickOnBubble(sf::Vector2i& mousePos, std::vector<Bubble *> bubbles, Bubble *& t)
Run Code Online (Sandbox Code Playgroud)

  • +1.第一个在C++环境中正确的答案.建议双向间接指针的答案是旧的C方式. (9认同)

And*_*rsK 20

如果你写

int b = 0;
foo(b);

int foo(int a)
{
  a = 1;
}
Run Code Online (Sandbox Code Playgroud)

你不改变'b',因为a是b的副本

如果你想改变b,你需要传递b的地址

int b = 0;
foo(&b);

int foo(int *a)
{
  *a = 1;
}
Run Code Online (Sandbox Code Playgroud)

同样适用于指针:

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
}
Run Code Online (Sandbox Code Playgroud)

所以要改变b指向的地址:

int* b = 0;
foo(&b);

int foo(int** a)
{
  *a = 1;  // here you changing what b is pointing to
}
Run Code Online (Sandbox Code Playgroud)

心连心


mat*_*975 8

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

阅读这个问题以帮助理解更多细节的差异何时通过引用传递以及何时通过C++中的指针传递?