Home > Backend Development > C++ > Why Doesn't Modifying a Pointer in a C Function Change the Original Pointer?

Why Doesn't Modifying a Pointer in a C Function Change the Original Pointer?

Linda Hamilton
Release: 2024-12-27 07:17:09
Original
269 people have browsed it

Why Doesn't Modifying a Pointer in a C   Function Change the Original Pointer?

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
}
Copy after login

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
}
Copy after login

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
}
Copy after login

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!

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