A pointer is a variable that holds the address of an object. &x takes an address, *p follows it.
Basics
#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
}20 20 1
7
8 8| Expression | Meaning |
|---|---|
int* p; | Declare p as pointer to int (uninitialised — dangerous) |
int* p = nullptr; | Null pointer — points to nothing |
&x | Address of x |
*p | The object p points to (dereference) |
p->m | Member m of the pointed-to object = (*p).m |
p + n | Address n elements further (scaled by sizeof(T)) |
p[i] | *(p + i) |
Pointer arithmetic & arrays
#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)
}30 40
12345
5nullptr vs NULL vs 0
#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";
}f(int)
f(int*)
nullPointer dangers
#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
| Declaration | Can change *p? | Can change p? |
|---|---|---|
int* p | Yes | Yes |
const int* p (= int const* p) | No | Yes |
int* const p | Yes | No |
const int* const p | No | No |
What's the difference between a pointer and a reference?
What is the size of a pointer?