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

C++ Pointers Introduction

What is a Pointer?

A pointer is a variable whose value is a memory address rather than ordinary data, letting you refer to and manipulate exactly where another variable lives in memory rather than just its value. This indirection is what enables techniques like dynamic memory allocation and passing large data efficiently without copying it.

Example: What is a Pointer?

cpp
#include <iostream>

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

Declaring and Initializing Pointers

Declaring a pointer places an asterisk between the type and the variable name, like int *ptr;, and the address-of operator & retrieves a variable's actual memory address, so ptr = &age; makes ptr point directly at where age lives in memory.

Example: Declaring and Initializing Pointers

cpp
#include <iostream>

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

Dereferencing Pointers

The dereference operator, also written as * but used differently here — *ptr — accesses or modifies the actual value stored at the address the pointer holds, rather than the address itself. So *ptr = 30; changes the original variable's value through the pointer, not the pointer itself.

Example: Dereferencing Pointers

cpp
#include <iostream>

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

Printing Memory Addresses

Printing a pointer variable directly, without dereferencing it, outputs the memory address it holds — usually shown as a hexadecimal number like 0x7ffee3a1c05c — which is useful for debugging but tells you nothing about the actual value stored at that address unless you dereference it too.

Example: Printing Memory Addresses

cpp
#include <iostream>

int main() {
	int value = 5;
	int *ptr = &value;
	std::cout << ptr << std::endl; // prints the address, not the value
	return 0;
}

Null Pointers

A pointer that isn't currently pointing at any valid variable should explicitly be set to nullptr rather than left uninitialized, since an uninitialized wild pointer holds a garbage address that could point anywhere in memory. Dereferencing a nullptr still crashes the program, but it does so predictably and is far easier to debug than a wild pointer corrupting unrelated memory.

Example: Null Pointers

cpp
#include <iostream>

int main() {
	int *ptr = nullptr;
	if (ptr == nullptr) {
		std::cout << "Pointer is not pointing anywhere yet" << 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.