Function does not change passed pointer C++
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.
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?
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];
}
You are passing the pointer by value.
Pass a reference to the pointer if you want it updated.
bool clickOnBubble(sf::Vector2i& mousePos, std::vector<Bubble *> bubbles, Bubble *& t)
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
if you want to change b you would need to pass the address of 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:
int* b = 0;
foo(&b);
int foo(int** a)
{
*a = 1; // here you changing what b is pointing to
}
hth
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++?