Learn C++
#include "arrayspointers/pointers.hpp"

Pointers Basics in C++

//concept

A pointer is a variable holding a memory address: int* p = &x; stores x's address in p, *p reads or writes x through it, and & takes addresses. This indirection powers dynamic allocation, polymorphic dispatch, and data structures built from linked nodes — plus the entire C ecosystem.

The discipline is non-negotiable: initialize every pointer (nullptr when no target yet), check for nullptr before dereferencing, and never use a pointer after its pointee dies. Modern C++ pushes raw pointers to non-owning roles, with smart pointers owning — but you must master raw mechanics first.

//how it works
1

& takes, * follows

&x is x's address; if p holds it, *p is x itself. & and * are inverse operations across the declaration/use divide.

2

Declare carefully

int* p reads as pointer-to-int. Write int* p (not int *p) and declare one pointer per line — int* a, b makes b a plain int.

3

nullptr, always initialized

Pointers start life as garbage like ints do — int* p = nullptr; marks empty explicitly and crashes loudly (not silently) if misused.

4

Never dangle

A pointer to a destroyed local or freed block is a time bomb. Null it, reassign it, or scope it — never dereference the dead.

//example
#include <iostream>
 
int main() {
int x = 10;
int* p = &x;
*p = 20;
std::cout << x << ", " << *p << std::endl;
return 0;
}
Output
20, 20
1&x captures x's address into p — p now points at x's memory slot.
2*p = 20 writes through the pointer, changing x itself to 20.
3Both x and *p read 20 because they name the same storage two ways.
//use cases
Dynamic structures (linked lists, trees) where nodes point at each other
Optional out-parameters and nullable handles via nullptr conventions
Polymorphic calls through base-class pointers (virtual dispatch needs them)
Interfacing with C APIs that speak exclusively in pointers

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.