Home >Backend Development >C++ >When Should You Pass Pointers by Reference in C ?
In C , passing pointers by reference is a technique employed under specific circumstances: when a pointer itself needs to be modified within a function rather than the object it points to. This approach differs from the conventional method of passing pointers by value, which involves copying the address of the object.
The code provided exemplifies this scenario:
void foo(type *&in) {...} void fii() { type *choochoo; ... foo(choochoo); }
Within function fii, a pointer choochoo is created and subsequently passed as an argument to function foo. By passing the pointer by reference, as indicated by the ampersand & before the asterisk *, the function foo is granted the ability to modify the pointer choochoo itself, rather than creating a copy.
This technique holds similarities to the use of double pointers. However, referencing a pointer provides an additional layer of protection, reducing the likelihood of errors compared to using pointers directly.
Therefore, the primary motivation for passing a pointer by reference is the need to alter the pointer within a function, ensuring that the modification is propagated back to the calling function.
The above is the detailed content of When Should You Pass Pointers by Reference in C ?. For more information, please follow other related articles on the PHP Chinese website!