Pointer dereference
- C++ course
- Beginner
- Lesson 79/116
- 5 min
Learn to access the value a pointer points to with *.
Pointer dereference
The * operator (dereference) accesses the value at the address a pointer holds. After int* p = &x;, writing *p reads the value of x.
* is used not only to read but also to write. Writing *p = 20; sets x's value to 20, because p holds x's address. This is the basis of pass by pointer and one of the strongest features of pointers.
Dereference assignment
By writing *p = value;, you change the variable the pointer points to. This is like using the pointer as a 'remote control'; even if p is in another function, *p affects the original variable.
This feature is used so functions can modify the caller's variables. For example void setToZero(int* p) { *p = 0; } resets the variable whose address was passed. Pointer parameters resemble reference parameters in this regard.
Practice Modify through a pointer
Declare int x = 10;. Bind with int* p = &x;. Change x's value by writing *p = 20;. Print x with std::cout.
Starter code
#include <iostream>
int main() {
// Declare x
// Bind p as a pointer to x
// Change x through *p
// Print x
return 0;
}Sample solution
#include <iostream>
int main() {
int x = 10;
int* p = &x;
*p = 20;
std::cout << x << "\n";
return 0;
}Expected output
20
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does this code print?
int x = 10;
int* p = &x;
*p = 20;
std::cout << x;- Error
- 10
- 0
- 20 Correct answer
Explanation: *p = 20 makes x become 20, because p points to x.
2 Match each expression to its meaning
| Term | Meaning |
|---|---|
*p |
Access value |
*p = 20 |
Change value |
int* p = &x |
Binding |
x |
Target variable |
3 Dereference
std::cout << ____;
std::cout << *p;
Explanation: std::cout << *p; prints the value p points to.