Home > Backend Development > C++ > Pointers in C : Pass by Value vs. Pass by Reference—Which Should I Use?

Pointers in C : Pass by Value vs. Pass by Reference—Which Should I Use?

Barbara Streisand
Release: 2024-12-30 09:53:09
Original
537 people have browsed it

Pointers in C  : Pass by Value vs. Pass by Reference—Which Should I Use?

Passing Pointers by Value vs. by Reference

When passing pointers to functions, it is important to understand the difference between passing by value and passing by reference.

In the example provided, the function clickOnBubble is attempting to set the value of targetBubble to a pointer stored in the bubbles vector. However, the function is only passing a copy of targetBubble to the function, so any changes made to the copy within the function will not be reflected in the original pointer.

Passing by Reference with Pointer-to-Pointer

To change the original pointer, it is necessary to pass it by reference. This can be done using a pointer-to-pointer, as shown in the following code:

void foo(int **ptr) {
    *ptr = new int[10]; // Just for example, use RAII in a real-world application
}
Copy after login

In this example, ptr is a pointer to a pointer. When the function is called, the address of targetBubble is passed to the function. The function can then use the double indirection operator (**) to access and modify the original targetBubble pointer.

Passing by Reference with Reference-to-Pointer

Another way to pass a pointer by reference is to use a reference-to-pointer, as shown in the following code:

void bar(int *&ptr) {
    ptr = new int[10];
}
Copy after login

Here, ptr is a reference to a pointer. When the function is called, the reference is bound to targetBubble. The function can then modify targetBubble directly through the reference.

The above is the detailed content of Pointers in C : Pass by Value vs. Pass by Reference—Which Should I Use?. 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