Skip to content
  • Pointers · C++

Pointers

LearnViaNotes @learnvianotes· 3 min read

A pointer is a variable that holds the address of an object. &x takes an address, *p follows it.

Basics

C++
#include <iostream>
int main() {
    int x = 10;
    int* p = &x;          // p holds x's address
    *p = 20;              // write through the pointer
    std::cout << x << ' ' << *p << ' ' << (p == &x) << '\n';

    int y = 7;
    p = &y;               // re-point to another object
    std::cout << *p << '\n';

    int** pp = &p;        // pointer to pointer
    **pp = 8;
    std::cout << y << ' ' << sizeof(p) << '\n';   // every data pointer is 8 bytes on 64-bit
}
Output
20 20 1
7
8 8
ExpressionMeaning
int* p;Declare p as pointer to int (uninitialised — dangerous)
int* p = nullptr;Null pointer — points to nothing
&xAddress of x
*pThe object p points to (dereference)
p->mMember m of the pointed-to object = (*p).m
p + nAddress n elements further (scaled by sizeof(T))
p[i]*(p + i)

Pointer arithmetic & arrays

C++
#include <iostream>
int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int* p = arr;                 // array decays to a pointer to its first element
    std::cout << *(p + 2) << ' ' << p[3] << '\n';
    int* end = arr + 5;           // one-past-the-end: may be compared, never dereferenced
    for (int* it = arr; it != end; ++it) std::cout << *it / 10;
    std::cout << '\n' << (end - p) << '\n';   // difference = number of elements (ptrdiff_t)
}
Output
30 40
12345
5

nullptr vs NULL vs 0

C++
#include <iostream>
void f(int)   { std::cout << "f(int)\n"; }
void f(int*)  { std::cout << "f(int*)\n"; }
int main() {
    f(0);          // 0 is an int → f(int)
    f(nullptr);    // nullptr has its own type → f(int*)
    int* p = nullptr;
    if (!p) std::cout << "null\n";
}
Output
f(int)
f(int*)
null

Pointer dangers

C++ — dangling pointer (ASan catches it)
#include <iostream>
int main() {
    int* p = nullptr;
    {
        int local = 5;
        p = &local;
    }                         // local destroyed here — p now dangles
    std::cout << *p << '\n';  // AddressSanitizer: stack-use-after-scope
}

const and pointers

DeclarationCan change *p?Can change p?
int* pYesYes
const int* p (= int const* p)NoYes
int* const pYesNo
const int* const pNoNo

What's the difference between a pointer and a reference?

What is the size of a pointer?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report