Reputation: 571
#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?
Upvotes: 0
Views: 706
Reputation: 1334
Your understanding of the code is correct. Sometimes it is easier to understand pointers to pointers and references of pointers, when you use aliases:
using int_ptr = int*;
void foo(int_ptr& ptr) // pass int_ptr by reference
{
ptr = nullptr; // change the int_ptr that is referenced
}
This kind of an alias usually shouldn't be used in real code.
Regarding
"null" is like nothing in C++, right? So nullptr is like a pointer which points to nothing?
Yes, nullptr
by definition does not point to an object or a function (and therefore must not be dereferenced). null
as a keyword does not exist in C++.
More info on null pointers in C++ here
Upvotes: 2
Reputation: 464
Yes, your understanding of the code is correct. Whenever you can, use analogy to simpler situations(like integers in your case) to understand things. A pointer is a variable which keeps a memory address. The null pointer concept means that a pointer points to nothing. You can find more about null concept here.
Upvotes: 0