Home >Backend Development >C++ >How Can I Modify a Pointer Passed to a C Function and Reflect Those Changes in the Calling Scope?

How Can I Modify a Pointer Passed to a C Function and Reflect Those Changes in the Calling Scope?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 10:15:16484browse

How Can I Modify a Pointer Passed to a C   Function and Reflect Those Changes in the Calling Scope?

Function Behavior: Passing Pointers in C

In C , passing a pointer to a function allows for modifying the original variable in the calling scope. However, certain nuances can arise when dealing with pointers.

Issue:

Consider a function that modifies a passed pointer, as in the following example:

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

Despite modifying the 'targetBubble' pointer within the function, changes are not reflected outside of it.

Reason and Solution:

The issue stems from passing a copy of the pointer rather than a reference to it. To rectify this, you can utilize the following techniques:

  1. Pointer to Pointer:
    Pass a pointer to the pointer, which allows you to modify the original pointer:

    void foo(int **ptr) //pointer to pointer
    {
        *ptr = new int[10]; //just for example, use RAII in a real world
    }
  2. Reference to Pointer:
    Pass a reference to the pointer, which directly modifies the original pointer:

    void bar(int *&ptr) //reference to pointer (a bit confusing look)
    {
        ptr = new int[10];
    }

By implementing either approach, you can effectively modify the pointer in the calling scope, ensuring that changes made within the function are reflected externally.

The above is the detailed content of How Can I Modify a Pointer Passed to a C Function and Reflect Those Changes in the Calling Scope?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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