#include <iostream> void foo(int *&ptr) // pass pointer by reference { ptr = nullptr; // this changes the actual ptr argument passed in, not a copy } int main() { int x = 5; int *ptr = &x; // create a pointer variable ptr, which is initialize with the memory address of x; that is, ptr is a pointer which is pointing to int variable x std::cout << "ptr is: " << (ptr ? "non-null" : "null") << '\n'; // prints non-null foo(ptr); std::cout << "ptr is: " << (ptr ? "non-null" : "null") << '\n'; // prints null return 0; } Here is how I understand it in the above code.
In the main function, firstly a local variable x is defined.
Then, a pointer variable with name ptr is defined, which is initialized with the memory address of x; i.e., ptr is a pointer variable which is pointing to the int variable x.
After that, check to see if ptr is null or not. Since it is initialized with a value, it is not-null?
After that, the function foo is called. Here, the parameter of the function int *&ptr can be understood as int* &ptr, i.e., this function foo accepts an int* (a pointer argument), and it is pass-by-reference because of the & in int* &ptr. Since it is pass-by-reference, the content of the pointer ptr is updated. So after the function call, the pointer variable ptr now has a value nullptr. That is why the very next std::cout would print null on the screen.
I hope I understand it correctly. An unrelated question: null is like nothing in C++, right? So nullptr is like a pointer which points to nothing?
"null"is just a string and your understanding of the code is correct.nullandnullptrcdeclaration type:void foo(int **ptr){}.