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 }
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]; }
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!