Pointers: &, * and nullptr
Declaring a pointer
int x = 42;
int* p = &x; // p holds the address of x
int*= "pointer to int"&x= "address of x"*p= "the value at the address in p" (dereference)
Reading and writing through a pointer
std::cout << *p; // 42
*p = 100; // x is now 100
The two meanings of * and &
| Where | * means | & means |
|---|---|---|
| In a declaration | "is a pointer" (int* p) | "is a reference" (int& r) |
| In an expression | dereference (*p) | address-of (&x) |
nullptr (C++11)
A pointer that points to nothing:
int* p = nullptr;
if (p) { ... } // false: safe check
*p; // ❌ crash (undefined behaviour)
✅ Use nullptr, not NULL or 0 — it has its own type and avoids overload confusion.
Uninitialized pointers ⚠️
int* p; holds a garbage address ("wild pointer"). Always initialize: to an address or nullptr.
Pointers to pointers
int** pp = &p; → **pp is the int. Used for arrays of strings and C APIs.
Pointers to class objects: ->
Account* a = &acc;
a->balance // same as (*a).balance
const and pointers (more in lesson 7.5)
const int* p — can't change the value through p.
Why pointers matter
- Dynamic memory (heap)
- Data structures: linked lists, trees, graphs
- Polymorphism (
Base*pointing toDerived) - Working with C libraries and hardware
- "Optional" references (nullptr means "none")
Example
#include <iostream>
#include <string>
struct Account {
std::string owner;
double balance;
};
void add_bonus(double* balance) { // pointer parameter
if (balance == nullptr) return; // always check before dereferencing
*balance += 500;
}
int main() {
int x = 42;
int* p = &x; // p stores the address of x
std::cout << "x = " << x << ", *p = " << *p << '\n';
std::cout << "p points to x? " << std::boolalpha << (p == &x) << '\n';
*p = 100; // change x through the pointer
std::cout << "after *p = 100, x = " << x << '\n';
int y = 7;
p = &y; // pointers can be re-pointed
std::cout << "now *p = " << *p << '\n';
int** pp = &p; // pointer to pointer
**pp = 8;
std::cout << "after **pp = 8, y = " << y << '\n';
int* nothing = nullptr;
std::cout << "nothing is " << (nothing ? "valid" : "nullptr") << '\n';
Account acc{ "Asha", 1000 };
Account* ap = &acc;
ap->balance += 250; // -> accesses members through a pointer
std::cout << ap->owner << " has " << (*ap).balance << '\n';
add_bonus(&acc.balance);
add_bonus(nullptr); // safely ignored
std::cout << "after bonus: " << acc.balance << '\n';
std::cout << "sizeof(int*) = " << sizeof(int*) << ", sizeof(Account*) = " << sizeof(Account*) << '\n';
return 0;
}
/* Output:
x = 42, *p = 42
p points to x? true
after *p = 100, x = 100
now *p = 7
after **pp = 8, y = 8
nothing is nullptr
Asha has 1250
after bonus: 1750
sizeof(int*) = 8, sizeof(Account*) = 8
*/