C++ Pointer Dereferencing
In this page:
The Dereference Operator *
The * operator, when applied to a pointer, follows the memory address it stores and gives access to the value found there -- this is called dereferencing the pointer.
Example: The Dereference Operator *
#include <iostream>
int main() {
int value = 10;
int *ptr = &value;
std::cout << *ptr << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Reading a Value Through a Pointer
Once a pointer holds a valid address, dereferencing it any number of times reads the current value at that address, always reflecting the latest value even if it changed after the pointer was set.
Example: Reading a Value Through a Pointer
#include <iostream>
int main() {
int value = 10;
int *ptr = &value;
value = 20;
std::cout << *ptr << std::endl; // reflects the latest value
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Dereferencing and Data Types
The type a pointer was declared with determines how many bytes are read and how the resulting value is interpreted when it's dereferenced, which is why a pointer's declared type must match what it actually points to.
Example: Dereferencing and Data Types
#include <iostream>
int main() {
double value = 3.14;
double *ptr = &value;
std::cout << *ptr << std::endl; // reads 8 bytes as a double
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Dereferencing a Null Pointer
Dereferencing a null pointer, one that hasn't been assigned a valid address, is undefined behavior and typically crashes the program, so a pointer should always be checked or known to be valid before dereferencing.
Example: Dereferencing a Null Pointer
#include <iostream>
int main() {
int *ptr = nullptr;
if (ptr != nullptr) {
std::cout << *ptr << std::endl;
} else {
std::cout << "Cannot dereference a null pointer" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Dereferencing Combined with Arrow ->
For a pointer to a struct or class, (*ptr).member and ptr->member are equivalent ways to dereference the pointer and access one of its members, with -> being the shorter, more common form.
Example: Dereferencing Combined with Arrow ->
#include <iostream>
struct Point { int x; int y; };
int main() {
Point p = {3, 4};
Point *ptr = &p;
std::cout << (*ptr).x << " " << ptr->x << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: