Home > Backend Development > C++ > Why Doesn't My Pointer Change After Passing It to a Function?

Why Doesn't My Pointer Change After Passing It to a Function?

Patricia Arquette
Release: 2024-12-26 12:23:10
Original
1053 people have browsed it

Why Doesn't My Pointer Change After Passing It to a Function?

Understanding the Issue: Unmodified Pointer Passing

In this code snippet, the clickOnBubble function receives a pointer to a Bubble object (targetBubble) and a vector of Bubble pointers (bubbles). The issue is that after the function is executed, the targetBubble pointer passed to the function remains unmodified. The expectation is that the function should change the targetBubble pointer to point to a specific Bubble in the bubbles vector, but this is not happening.

Passing a Copy of the Pointer

The reason for this behavior is that you are passing a copy of the targetBubble pointer, not a reference. When you pass a copy of a pointer, any changes made to the pointer within the function will not be reflected in the original pointer outside the function.

Solution: Using a Pointer Reference or Pointer to Pointer

To ensure that the targetBubble pointer outside the function is changed, you need to pass a reference to the pointer or use a pointer to pointer.

Using a Pointer Reference:

void clickOnBubble(sf::Vector2i &mousePos, std::vector<Bubble *>& bubbles, Bubble *&targetBubble) {
    targetBubble = bubbles[i]; // Modified pointer here is reflected outside function
}
Copy after login

Using a Pointer to Pointer:

void clickOnBubble(sf::Vector2i &mousePos, std::vector<Bubble *>& bubbles, Bubble **targetBubble) {
    *targetBubble = bubbles[i]; // Modified pointer here is reflected outside function
}
Copy after login

In both cases, the modified targetBubble pointer within the function will be reflected in the original targetBubble pointer outside the function.

The above is the detailed content of Why Doesn't My Pointer Change After Passing It to a Function?. 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