2012-08-07 99 views
26

我有我的功能,我填写targetBubble那里,但它没有填充后调用此函数,但我知道它填写了这个函数,因为我有那里的输出代码。功能不改变通过指针C++

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

而且我传递指针这样

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

为什么它不工作吗?谢谢

回答

61

因为您传递指针的副本。要改变指针你需要的东西是这样的:

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]; 
} 
+0

但是当我尝试你的计算策略会崩溃在这一行'* targetBubble =气泡[I]'我我正在传递像'clickOnBubble(mousePos,bubbles,&targetBubble)这样的参数;' – c0ntrol 2012-08-07 09:28:15

+0

@ user1295618:你看到了什么错误?可能我超出范围 – Andrew 2012-08-07 09:35:13

+0

分段错误 – c0ntrol 2012-08-07 09:41:37

6

除非你(非常数)引用或作为双指针通过它你不能改变指针。按值传递会生成对象的副本,并且对该对象所做的任何更改都将作为副本,而不是对象。您可以更改指针指向的对象,但如果按值传递,则不会指向指针本身。

有这个问题的读取,以帮助了解更详细When to pass by reference and when to pass by pointer in C++?

19

您是按值传递指针的差异。

如果您想更新,请通过参考指针

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

将不会出现问题+1。第一个答案是在C++环境下正确的。建议双重间接指针的答案是旧C的做法。 – paxdiablo 2012-08-07 09:02:28

14

,如果你写

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 
} 

心连心