Function Does Not Alter Passed Pointer in C
In C , the confusion arises when attempting to modify a pointer passed to a function. The issue lies in the inherent nature of pointers. When a function receives a pointer as an argument, it actually operates on a copy of that pointer, not the original pointer itself.
Consider the example function clickOnBubble:
bool clickOnBubble(sf::Vector2i &mousePos, std::vector<Bubble *>& bubbles, Bubble *targetBubble) { // ... your code }
When you pass a pointer as a parameter, the function creates a new copy of that pointer within its local scope. Any modifications made to the local copy of the pointer will not affect the original pointer outside the function. In the above scenario, the code attempts to assign targetBubble to an element of the bubbles vector within the function, but this assignment only modifies the local copy of targetBubble.
To effectively modify the pointer outside the function, either use a pointer to a pointer or a reference to a pointer. This allows the function to access and modify the original pointer.
Using a Pointer to a Pointer:
void foo(int **ptr) { *ptr = new int[10]; // Assign memory to the pointed-to location }
In this example, the function foo takes a pointer to a pointer as its argument. It can now modify the pointer itself, assigning a new value to it.
Using a Reference to a Pointer:
void bar(int *&ptr) { ptr = new int[10]; // Assign memory to the pointed-to location }
Here, the function bar takes a reference to a pointer. It can access and modify the original pointer directly.
The above is the detailed content of Why Doesn't Modifying a Pointer in a C Function Change the Original Pointer?. For more information, please follow other related articles on the PHP Chinese website!