Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 869
c0ntrol Avatar asked Aug 07 '12 08:08

c0ntrol


People also ask

What happens when you pass a pointer to a function in C?

Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.

Can a pointer be changed within function?

Pointers are passed as values, if you want to change a pointer, you have to pass a pointer to a pointer. A pointer as function parameter is basically a local variable, the changes only affect the pointer in this scope.

Is pointer passed by value in C?

Yes to both. Pointers are passed by value as anything else.


1 Answers

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]; } 
like image 199
Andrew Avatar answered Sep 26 '22 08:09

Andrew