函数不会改变传递的指针 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11842416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Function does not change passed pointer C++
提问by c0ntrol
I have my function and I am filling targetBubble
there, but it is not filled after calling this function, but I know it was filled in this function because I have there output code.
我有我的函数,我正在targetBubble
那里填充,但是在调用这个函数后它没有被填充,但我知道它被填充在这个函数中,因为我有输出代码。
bool clickOnBubble(sf::Vector2i & mousePos, std::vector<Bubble *> bubbles, Bubble * targetBubble) {
targetBubble = bubbles[i];
}
And I am passing the pointer like this
我像这样传递指针
Bubble * targetBubble = NULL;
clickOnBubble(mousePos, bubbles, targetBubble);
Why it is not working please? Thanks
为什么它不起作用?谢谢
回答by Andrew
Because you are passing a copy of pointer. To change the pointer you need something like this:
因为您正在传递指针的副本。要更改指针,您需要这样的东西:
void foo(int **ptr) //pointer to pointer
{
*ptr = new int[10]; //just for example, use RAII in a real world
}
or
或者
void bar(int *& ptr) //reference to pointer (a bit confusing look)
{
ptr = new int[10];
}
回答by Daniel Daranas
You are passing the pointer by value.
您正在按值传递指针。
Pass a reference to the pointerif you want it updated.
如果您希望它更新,请传递对指针的引用。
bool clickOnBubble(sf::Vector2i& mousePos, std::vector<Bubble *> bubbles, Bubble *& t)
回答by AndersK
if you write
如果你写
int b = 0;
foo(b);
int foo(int a)
{
a = 1;
}
you do not change 'b' because a is a copy of b
你不改变 'b' 因为 a 是 b 的副本
if you want to change b you would need to pass the address of b
如果你想改变 b 你需要传递 b 的地址
int b = 0;
foo(&b);
int foo(int *a)
{
*a = 1;
}
same goes for pointers:
指针也是如此:
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
}
so to change where b points to pass the address:
所以要更改 b 指向传递地址的位置:
int* b = 0;
foo(&b);
int foo(int** a)
{
*a = 1; // here you changing what b is pointing to
}
hth
第
回答by mathematician1975
You cannot change the pointer unless you pass it by (non const) reference or as a double pointer. Passing by value makes a copy of the object and any changes to the object are made to the copy, not the object. You can change the object that the pointer points to, but not the pointer itself if you pass by value.
除非通过(非常量)引用或作为双指针传递指针,否则无法更改指针。按值传递会生成对象的副本,并且对对象的任何更改都会对副本进行,而不是对对象进行。如果按值传递,您可以更改指针指向的对象,但不能更改指针本身。
Have a read of this question to help understand the differences in more detail When to pass by reference and when to pass by pointer in C++?
阅读此问题以帮助更详细地了解差异,何时在 C++ 中通过引用传递和何时通过指针传递?