Hello, I’m Liang Tang.
This is part 34 of the EasyC++ series on the difference between references and Pointers.
If you want a better reading experience, you can visit github repository: EasyLeetCode.
Difference between reference and pointer
Pointers and references work very similarly, so they are often compared, especially in interviews.
This article will tease out some similarities and differences between references and Pointers.
The same
Both are about the idea of an address.
A pointer itself is a variable, storing a value as a memory address, and a reference as an alias for a memory. We can modify the value of the corresponding memory using Pointers or references.
The difference between
- References must be initialized at declaration time, while Pointers may not be
We cannot declare a variable reference and assign it a value. We can only initialize it at the same time:
int a = 3;
int &b; / / illegal
int &c = a; / / legal
Copy the code
Pointers do not have this limitation:
int *p; / / legal
Copy the code
- A reference can only be initialized once at declaration time and cannot point to another value after that, whereas a pointer can
References cannot be changed once declared, but Pointers can. In a way, a reference is like a constant pointer.
int a = 3;
int &b = a;
int const *p = &a;
Copy the code
- References must point to valid variables, and Pointers can be null
This is a big difference in the use of the two. We can take a reference and use it safely because it will never be empty. Pointers, on the other hand, may be null and must be judged before being used.
sizeof
Different results
The sizeof function calculates the sizeof a variable’s block of memory, but if we use sizeof a pointer, we get the sizeof the variable itself, not the sizeof the variable to which the pointer points. References don’t have this problem.
- A reference to a pointer, but no reference to a pointer
Let’s start with a pointer to a reference:
int a = 3;
int &b = a;
int *p = &b;
Copy the code
This code doesn’t give an error, but if we actually run it, we’ll see that p is just a normal int pointer to variable A. Because b is a reference, it has the same address as A. So if we define a pointer to B, we’re essentially defining a pointer to A. This is why Pointers to references don’t exist.
A reference to a pointer exists and is well understood, essentially an alias for a pointer:
int a = 3;
int *p = &a;
int *&pt = p;
Copy the code
Pt can also point to other variables and change the value of the dereference, so it is no different from p.
In addition to the above, Pointers and references differ in some subtle ways. For example, the meanings of autoincrement and autodecrement are different. The autoincrement and autodecrement of a pointer refer to the movement of the pointer, while the autoincrement and autodecrement of a reference refer to the change of the value of a variable.