Home > Backend Development > C++ > How Can I Modify a Pointer Variable from Within a Function in C ?

How Can I Modify a Pointer Variable from Within a Function in C ?

Linda Hamilton
Release: 2025-01-03 12:03:44
Original
592 people have browsed it

How Can I Modify a Pointer Variable from Within a Function in C  ?

Function Modifying Pointer Variable

The code provided involves a function clickOnBubble that attempts to modify a pointer variable targetBubble. However, the changes made within the function do not reflect in the caller's scope. This is because the function is passing a copy of the pointer, not a reference to it.

To modify a pointer variable from within a function, one needs to utilize a reference to pointer or a pointer to pointer.

Option 1: Reference to Pointer

In this approach, a reference to the pointer is passed as an argument to the function:

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

This reference allows the function to modify the value of the targetBubble pointer directly, affecting the original variable in the caller's scope.

Option 2: Pointer to Pointer

Alternatively, a pointer to pointer can be used:

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

In this case, the function receives a pointer to the targetBubble pointer. Modifying the value pointed to by the pointer (i.e., *targetBubble) indirectly changes the original targetBubble pointer in the caller's scope.

The above is the detailed content of How Can I Modify a Pointer Variable from Within a Function in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template