← Back to C++ Course | Chapter 7: Pointers & References | Lesson 2 of 11

C++ Pointer Dereferencing

Dereferencing a pointer with the * operator follows its stored address to access the actual value stored there, letting the pointed-to data be read or modified.

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 *

cpp
#include <iostream>

int main() {
	int value = 10;
	int *ptr = &value;
	std::cout << *ptr << std::endl;
	return 0;
}

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

cpp
#include <iostream>

int main() {
	int value = 10;
	int *ptr = &value;
	value = 20;
	std::cout << *ptr << std::endl; // reflects the latest value
	return 0;
}

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

cpp
#include <iostream>

int main() {
	double value = 3.14;
	double *ptr = &value;
	std::cout << *ptr << std::endl; // reads 8 bytes as a double
	return 0;
}

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

cpp
#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;
}

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 ->

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.