Every variable in your program lives somewhere in memory, and every memory location has a number called its address. So far we have always reached a variable through its name. A pointer is a variable that stores an address, which lets us reach a variable indirectly: "go to this address and use whatever is there".
Pointers are why C and C++ are so close to the hardware. They let a function change the caller's variables, let us walk through arrays efficiently, are the basis of dynamic memory, linked lists, trees and graphs, and appear in almost every C++ exam, GATE paper and placement test. They are also the source of the most dangerous bugs, so in this chapter we will be precise about what is allowed and what is undefined behaviour. We build on the Functions and Arrays topics.
What is a Pointer?
A pointer is a variable whose value is the memory address of another object (or function). The type of the pointer says what kind of object lives at that address, for example
int*is "pointer to int".
Think of memory as a long street of numbered houses. A normal variable is a house with something inside. A pointer is a slip of paper with a house number written on it. The slip is not the house, but by following it you can reach the house and even change what is inside.
int marks = 75;
int* p = &marks;
marks p
┌────────────┐ ┌────────────┐
│ 75 │◄─────────────│ 0x7ffc10 │
└────────────┘ └────────────┘
address 0x7ffc10 address 0x7ffc18
(4 bytes) (8 bytes on a 64-bit system)
The actual addresses are chosen by the system and change from run to run, so in this chapter we will rarely print them. What matters is the relationship: the value stored in p is the address of marks.
Declaring and Using Pointers
Two operators do all the basic work:
&(address-of):&marksgives the address ofmarks.*(dereference, or indirection):*pmeans "the object thatppoints to". It can be read and written.
#include <iostream>
int main() {
int marks = 75;
int* p = &marks; // p stores the address of marks
std::cout << "marks = " << marks << '\n';
std::cout << "*p = " << *p << '\n'; // value at that address
std::cout << std::boolalpha;
std::cout << "p == &marks: " << (p == &marks) << '\n';
*p = 90; // change marks THROUGH the pointer
std::cout << "marks now = " << marks << '\n';
int bonus = 5;
p = &bonus; // a pointer can be re-pointed
*p += 1;
std::cout << "bonus now = " << bonus << ", marks still " << marks << '\n';
}
Output:
marks = 75
*p = 75
p == &marks: true
marks now = 90
bonus now = 6, marks still 90
After p = &marks, the expression *p is just another name for marks. Writing *p = 90 changes marks itself. Then p = &bonus makes the pointer point somewhere else; marks is not affected by that.
The symbols * and & mean different things depending on where they appear. This confuses many beginners, so here it is in one table:
Where |
|
|
|---|---|---|
In a declaration: |
|
|
In an expression: | Dereference: the object pointed to | Address-of: the address of |
Between two values: | Multiplication | Bitwise AND |
Where Does the * Go?
int* p;, int *p; and int * p; all mean the same. But the * belongs to each name, not to the type, which leads to a classic trap:
int* a, b; // a is int*, but b is a plain int!
int *c, *d; // both are pointers
The simplest way to avoid this is to declare one pointer per line.
Null Pointers and nullptr
Sometimes a pointer has nothing to point to yet, or a search finds nothing. For that, C++11 introduced the keyword nullptr, a special value meaning "points to no object". A pointer holding it is a null pointer.
#include <iostream>
void show(int n) { std::cout << "show(int) called with " << n << '\n'; }
void show(int* p) { std::cout << "show(int*) called, "
<< (p ? "valid pointer" : "null pointer") << '\n'; }
// Stores the address of the first element equal to key in *where,
// or nullptr if there is none.
void find(int arr[], int n, int key, int** where) {
for (int i = 0; i < n; ++i) {
if (arr[i] == key) { *where = &arr[i]; return; }
}
*where = nullptr; // "points to nothing"
}
int main() {
show(0); // 0 is an int: picks show(int)
show(nullptr); // nullptr is a pointer: picks show(int*)
int data[] = {4, 8, 15, 16, 23};
int* hit = nullptr;
find(data, 5, 15, &hit);
if (hit != nullptr) std::cout << "found 15, *hit = " << *hit << '\n';
find(data, 5, 99, &hit);
if (!hit) std::cout << "99 not found, hit is null\n";
}
Output:
show(int) called with 0
show(int*) called, null pointer
found 15, *hit = 15
99 not found, hit is null
A null pointer converts to
false, any other pointer totrue, soif (p)andif (!p)are common shortcuts forp != nullptrandp == nullptr.Dereferencing a null pointer is undefined behaviour. On most systems the program crashes with a segmentation fault, but nothing is guaranteed. Always check a pointer that might be null before using
*.Older code uses
NULLor0. They are integer-like constants, which is whynullptrwas added:show(0)calls theintversion, and with GCCshow(NULL)does not compile at all ("call of overloaded 'show(NULL)' is ambiguous").nullptrhas its own type,std::nullptr_t, and always picks the pointer version. Usenullptrin all new code.findtakes anint**(a pointer to a pointer) so it can change the caller's pointerhit. We will look at that in detail below.
A pointer that has never been initialised (int* p; inside a function) is called a wild pointer. It holds some leftover bits, so it points at a random place. Even reading its value is undefined behaviour. Get into the habit of always initialising pointers, to nullptr if nothing better is available.
Pointer Arithmetic
When a pointer points into an array, you can move it with + and -. The key rule: arithmetic is done in elements, not bytes. If p points to an int, p + 1 points to the next int, which is sizeof(int) bytes further on.
#include <cstddef>
#include <cstdint>
#include <iostream>
int main() {
int a[5] = {10, 20, 30, 40, 50};
int* p = a; // array decays to &a[0]
std::cout << *p << ' ' << *(p + 1) << ' ' << *(p + 4) << '\n';
std::cout << a[2] << ' ' << *(a + 2) << ' ' << p[2] << '\n';
auto bytes = reinterpret_cast<std::uintptr_t>(p + 1)
- reinterpret_cast<std::uintptr_t>(p);
std::cout << "p + 1 is " << bytes << " bytes after p\n";
double d[3] = {1.5, 2.5, 3.5};
double* q = d;
auto dbytes = reinterpret_cast<std::uintptr_t>(q + 1)
- reinterpret_cast<std::uintptr_t>(q);
std::cout << "q + 1 is " << dbytes << " bytes after q\n";
int* end = a + 5; // one past the last element: allowed
std::ptrdiff_t count = end - p; // number of ELEMENTS between them
std::cout << "end - p = " << count << '\n';
for (int* it = a; it != end; ++it) { // walk the array with a pointer
std::cout << *it << ' ';
}
std::cout << '\n';
++p; // p now points to a[1]
int v = *p++; // read a[1], then move p to a[2]
std::cout << "*p++ gave " << v << ", now *p = " << *p << '\n';
}
Output:
10 20 50
30 30 30
p + 1 is 4 bytes after p
q + 1 is 8 bytes after q
end - p = 5
10 20 30 40 50
*p++ gave 20, now *p = 30
a[0] a[1] a[2] a[3] a[4]
┌──────┬──────┬──────┬──────┬──────┐
│ 10 │ 20 │ 30 │ 40 │ 50 │
└──────┴──────┴──────┴──────┴──────┘
byte: 1000 1004 1008 1012 1016 1020
▲ ▲ ▲
p p + 1 p + 5 (end)
(The byte numbers are made up for the picture; only the gaps of 4 matter.) Here is what is and is not allowed:
Operation | Meaning | Allowed? |
|---|---|---|
| Move by | Yes, as long as the result stays inside the same array or one past its end |
| Number of elements between them (type | Only if both point into the same array (or one past it) |
| Same address? | Yes, always |
| Which comes first? | Meaningful within one array; for unrelated objects the result is unspecified |
| Nothing sensible | No, does not compile |
| Read past the end | Undefined behaviour |
A subtle point: forming a pointer that is outside the array (other than exactly one past the end) is already undefined behaviour, even if you never dereference it. The "one past the end" pointer is special: you may compute it and compare with it, which is exactly how the loop for (int* it = a; it != end; ++it) works, but you must not dereference it.
*p++ and Friends
Postfix ++ has higher precedence than unary *, so *p++ means *(p++): use the value p points to, then move p forward. The four forms that appear in exam questions:
Expression | Same as | Effect |
|---|---|---|
|
| Value at |
|
|
|
|
| Increments the pointed-to value; |
| (already explicit) | Value at |
Pointers and Arrays
In the Arrays topic we said that an array name "decays" to the address of its first element. Now we can say it precisely:
Array-to-pointer decay: in most expressions, an array of type
T[N]is automatically converted to aT*pointing to its first element. The subscripta[i]is defined as*(a + i).
That is why a[2], *(a + 2) and p[2] all printed 30 above, and why indexes start at 0: a[0] is *(a + 0), the first element. Because a + i and i + a are the same, i[a] is also legal (and equal to a[i]). Nobody writes it in real code, but it loves to appear in quizzes.
However, an array is not a pointer. Decay does not happen with sizeof, with &a, or when an array is bound to a reference:
#include <iostream>
int main() {
int a[10] = {};
int* p = a;
std::cout << "sizeof(a) = " << sizeof(a) << '\n';
std::cout << "sizeof(p) = " << sizeof(p) << '\n';
std::cout << "sizeof(char*) = " << sizeof(char*) << '\n';
std::cout << "sizeof(double*) = " << sizeof(double*) << '\n';
std::cout << "sizeof(int**) = " << sizeof(int**) << '\n';
}
Output (on a typical 64-bit system):
sizeof(a) = 40
sizeof(p) = 8
sizeof(char*) = 8
sizeof(double*) = 8
sizeof(int**) = 8
Array | Pointer | |
|---|---|---|
What it is | 10 ints stored together | One variable holding one address |
| 40 (whole array) | 8 (just the address) |
Can be re-assigned? | No: | Yes: |
| Not allowed | Allowed |
As a function parameter |
| Same |
The last row is the "sizeof trap" from the Arrays topic: inside a function, a parameter declared as an array is really a pointer, so sizeof gives the pointer size, not the array size. All pointer types happen to be 8 bytes on mainstream 64-bit systems (4 bytes on 32-bit ones), whatever they point to, because they all store one address.
Passing Pointers to Functions
In the Functions topic we saw that arguments are normally passed by value: the function gets a copy. If you pass the address of a variable, the function can reach and change the original:
#include <iostream>
void swapByValue(int x, int y) { // works on copies
int t = x; x = y; y = t;
}
void swapByPointer(int* x, int* y) { // works on the originals
int t = *x;
*x = *y;
*y = t;
}
void minMax(const int arr[], int n, int* mn, int* mx) { // two "results"
*mn = *mx = arr[0];
for (int i = 1; i < n; ++i) {
if (arr[i] < *mn) *mn = arr[i];
if (arr[i] > *mx) *mx = arr[i];
}
}
int main() {
int a = 3, b = 7;
swapByValue(a, b);
std::cout << "after swapByValue: a=" << a << " b=" << b << '\n';
swapByPointer(&a, &b);
std::cout << "after swapByPointer: a=" << a << " b=" << b << '\n';
int marks[] = {67, 92, 45, 88, 71};
int lo, hi;
minMax(marks, 5, &lo, &hi);
std::cout << "min=" << lo << " max=" << hi << '\n';
}
Output:
after swapByValue: a=3 b=7
after swapByPointer: a=7 b=3
min=45 max=92
swapByValue swapped its own copies, which were thrown away when it returned. swapByPointer received the addresses of a and b, and *x = *y changed the real variables. Strictly speaking, the pointers themselves were still passed by value (the function got copies of the addresses), but a copy of an address still leads to the same house.
minMax shows the other big use: a function can return only one value, but through pointer parameters it can hand back several results. The array parameter is const int arr[] because the function only reads it. In C++ the same job is usually done more cleanly with references, which is the subject of the next topic, References. You still need pointers whenever "no object" (null) is a valid argument, and for arrays and C libraries.
const and Pointers
With a pointer there are two things that could be read-only: the object it points to, and the pointer itself. Where you put const decides which:
#include <iostream>
int main() {
int x = 1, y = 2;
const int* p1 = &x; // pointer to const int: *p1 is read-only
p1 = &y; // OK: the pointer itself may change
std::cout << *p1 << '\n';
int* const p2 = &x; // const pointer to int: always points to x
*p2 = 10; // OK: the int may change
std::cout << x << '\n';
const int* const p3 = &y; // neither may change
std::cout << *p3 << '\n';
const char* msg = "Hello"; // string literals are const char arrays
std::cout << msg << '\n';
}
Output:
2
10
2
Hello
Breaking the rules is caught at compile time:
int main() {
int x = 1, y = 2;
const int* p1 = &x;
*p1 = 5; // error: *p1 is read-only
int* const p2 = &x;
p2 = &y; // error: p2 itself is const
}
p06_nocompile_const.cpp: In function ‘int main()’:
p06_nocompile_const.cpp:4:9: error: assignment of read-only location ‘* p1’
4 | *p1 = 5; // error: *p1 is read-only
| ~~~~^~~
p06_nocompile_const.cpp:6:8: error: assignment of read-only variable ‘p2’
6 | p2 = &y; // error: p2 itself is const
| ~~~^~~~
The trick for reading these declarations is to read right to left, starting from the name:
Declaration | Read as | Change | Change |
|---|---|---|---|
| p is a pointer to int | Yes | Yes |
| p is a pointer to const int | No | Yes |
| p is a const pointer to int | Yes | No |
| p is a const pointer to const int | No | No |
const int* is the one you will use most: it is how a function promises "I will only read through this pointer". You can pass an int* where a const int* is expected (adding const is safe), but not the other way round. Note that "pointer to const" only means you cannot modify the object through this pointer; in the program above, x itself is not const and can still be changed directly.
Pointer to Pointer
A pointer is a variable too, so it has an address, and that address can be stored in a pointer to pointer, int**.
#include <iostream>
// Makes the caller's pointer point to the larger of *a and *b.
void pointToLarger(int** pp, int* a, int* b) {
*pp = (*a > *b) ? a : b; // change the pointer the caller owns
}
int main() {
int x = 5;
int* p = &x;
int** pp = &p; // pointer to a pointer to int
std::cout << x << ' ' << *p << ' ' << **pp << '\n';
**pp = 50; // pp -> p -> x
std::cout << "x = " << x << '\n';
int m = 12, n = 40;
int* best = nullptr;
pointToLarger(&best, &m, &n);
std::cout << "larger = " << *best << '\n';
}
Output:
5 5 5
x = 50
larger = 40
pp p x
┌──────────┐ ┌──────────┐ ┌──────────┐
│ &p │──────►│ &x │──────►│ 50 │
└──────────┘ └──────────┘ └──────────┘
*pp is p **pp is x
Why would you need one? For the same reason as before: to change a variable from inside a function you pass its address. If the variable you want to change is itself a pointer (like best or hit), you pass the address of a pointer, so the parameter type is int**. Pointers to pointers also appear in dynamically allocated 2D arrays, which we will build in the Dynamic Memory Allocation topic.
Dangling Pointers
A dangling pointer is a pointer that still holds the address of an object whose lifetime has ended. Dereferencing it is undefined behaviour.
A local variable lives only until the end of the block that declares it. A pointer to it does not know that:
#include <iostream>
int main() {
int* p = nullptr;
{
int temp = 42;
p = &temp;
std::cout << "inside the block: " << *p << '\n';
} // temp's lifetime ends here
std::cout << "after the block: " << *p << '\n'; // undefined behaviour
}
A normal build will probably print 42 twice and seem to work, which is exactly what makes this bug dangerous. (GCC 12 and later can spot this simple case with -Wall: "using dangling pointer ‘p’ to ‘temp’ [-Wdangling-pointer=]", but it misses most real-world cases.) Built with g++ -std=c++23 -g -fsanitize=address,undefined, the access is caught. Output (trimmed; addresses differ on every run):
inside the block: 42
=================================================================
==1194==ERROR: AddressSanitizer: stack-use-after-scope on address 0x75ed9b2f0020 ...
READ of size 4 at 0x75ed9b2f0020 thread T0
#0 0x5836042ac750 in main p09_asan_dangling.cpp:10
...
[32, 36) 'temp' (line 6) <== Memory access at offset 32 is inside this variable
The most famous version is returning the address of a local variable from a function. GCC warns about it even without the sanitizer:
int* makeNumber() {
int n = 42;
return &n; // n dies when the function returns
}
p10_warn_return_local.cpp: In function ‘int* makeNumber()’:
p10_warn_return_local.cpp:3:12: warning: address of local variable ‘n’ returned [-Wreturn-local-addr]
3 | return &n; // n dies when the function returns
| ^~
p10_warn_return_local.cpp:2:9: note: declared here
2 | int n = 42;
| ^
Treat this warning as an error. The local variable n is destroyed when makeNumber returns, so the caller receives an address that no longer belongs to any object. (Returning a copy of the value, int makeNumber(), is the correct fix.) The third classic way to get a dangling pointer, using memory after delete, is covered in the Dynamic Memory Allocation topic.
Bad pointer | What it holds | How to avoid it |
|---|---|---|
Wild (uninitialised) | Random leftover bits | Always initialise, to |
Null |
| Check before dereferencing |
Dangling | Address of a dead object | Never let a pointer outlive what it points to |
Out of range | Address past the end of an array | Keep arithmetic within the array or one past its end |
void Pointers
A void* is a "generic" pointer: it can hold the address of any object, but it does not know the type of what is there.
#include <iostream>
int main() {
int i = 7;
double d = 2.5;
void* vp = &i; // void* can hold the address of any object
std::cout << *static_cast<int*>(vp) << '\n'; // must cast back before use
vp = &d;
std::cout << *static_cast<double*>(vp) << '\n';
}
Output:
7
2.5
You cannot dereference a
void*; the compiler does not know how many bytes to read or how to interpret them. Cast it back to the correct type first.Pointer arithmetic on
void*is not allowed in standard C++ (GCC accepts it as an extension).Any object pointer converts to
void*automatically, but in C++ (unlike C) going back needs an explicit cast. Casting it to the wrong type and dereferencing is undefined behaviour.You will meet
void*mainly in C library functions such asmemcpyandmalloc. In C++ code, templates (see the Templates topic) are the type-safe way to write generic code.
Function Pointers
Functions also live at addresses, so you can have a pointer to a function. The syntax looks strange at first: int (*f)(int, int) reads as "f is a pointer to a function taking two ints and returning int". The brackets around *f matter; without them, int* f(int, int) would declare a function returning int*.
#include <iostream>
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int apply(int (*op)(int, int), int x, int y) { // op is a function pointer
return op(x, y);
}
int main() {
int (*f)(int, int) = add; // a function name converts to its address
std::cout << f(3, 4) << '\n';
f = mul;
std::cout << f(3, 4) << '\n';
std::cout << apply(add, 10, 5) << ' ' << apply(mul, 10, 5) << '\n';
}
Output:
7
12
15 50
Passing a function to another function (here apply) is called a callback. The C library's qsort works this way. In modern C++ you will more often pass lambdas, covered in the Lambda Expressions topic, but function pointers are still common in C APIs and in exam questions.
Pointers in Modern C++
Raw pointers are not "old-fashioned" and you will use them, but modern C++ gives each of their jobs a safer tool:
Job | Raw pointer way | Usually better |
|---|---|---|
Let a function modify a caller's variable |
|
|
Optional object ("maybe nothing") | Pointer that may be | A raw pointer is fine for non-owning access; |
Pass an array and its size |
|
|
Own memory from |
|
|
Generic code |
| Templates |
The guiding rule used by the C++ Core Guidelines: a raw pointer T* should be non-owning. It may look at an object, but it is never responsible for deleting it.
Common Mistakes
Using an uninitialised pointer.
int* p; *p = 5;writes to a random address. Initialise every pointer.Dereferencing without checking for null when a function may return
nullptr.Writing
int* a, b;and expecting two pointers.Returning the address of a local variable, or keeping a pointer to a variable after its block ends.
Going past the end of an array with pointer arithmetic, often by one in a
<=loop.Confusing
*p++with(*p)++. The first moves the pointer, the second changes the value.Using
sizeof(arr)on an array parameter, which is really a pointer.Comparing C-strings with
==, which compares addresses (see the Strings topic).Using
NULLor0instead ofnullptr, which can pick the wrong overload or make a call ambiguous.
Interview and GATE Questions
What is the output of this program?
int a[] = {2, 4, 6, 8, 10};
int* p = a + 1;
int* q = &a[4];
std::cout << *p + 1 << '\n';
std::cout << *(p + 1) << '\n';
std::cout << q - p << '\n';
*q-- = 0;
std::cout << *q << ' ' << a[4] << '\n';
std::cout << p[-1] + 3[a] << '\n';
5
6
3
8 0
10
p points to a[1] (4) and q to a[4] (10). *p + 1 is (*p) + 1 = 5. *(p + 1) is a[2] = 6. q - p = 4 − 1 = 3 elements. *q-- = 0 is *(q--) = 0: it sets a[4] to 0, then moves q back to a[3] (8). Finally p[-1] is *(p - 1) = a[0] = 2 (a negative index is fine because it stays inside the array), and 3[a] is a[3] = 8, giving 10.
What is the size of a pointer?
It depends on the platform, not on the type pointed to: typically 8 bytes on 64-bit systems and 4 bytes on 32-bit systems. The standard does not actually require all pointer types to have the same size, but on all mainstream platforms object pointers do.
What is the difference between const int* p and int* const p?
const int* p is a pointer to a const int: *p = 5 is an error, but p can point elsewhere. int* const p is a const pointer: it must be initialised and always points to the same int, but that int can be changed through it.
Why was nullptr introduced when we already had NULL?
NULL is an integer-like constant (0 or a compiler-specific equivalent), so with overloads such as f(int) and f(int*) the call f(NULL) picks the wrong function or is ambiguous. nullptr (C++11) has its own type, std::nullptr_t, which converts to any pointer type but not to integers.
If int a[10]; starts at address 1000 and an int is 4 bytes, what is the address of a + 3 and of &a + 1?
a + 3 moves 3 ints: 1000 + 3 × 4 = 1012. &a is a pointer to the whole array (type int(*)[10], size 40 bytes), so &a + 1 moves one whole array: 1000 + 40 = 1040. So a and &a hold the same address but have different types, and arithmetic on them moves by different amounts.
What is a dangling pointer, and how is it different from a wild pointer?
A dangling pointer once pointed to a valid object, but that object's lifetime has ended (a local variable went out of scope, or heap memory was deleted). A wild pointer was never initialised at all. Using either is undefined behaviour.
Can you do arithmetic on a void*?
Not in standard C++, because the size of void is unknown, so the compiler cannot tell how far "+1" should move. GCC allows it as an extension (treating the size as 1). Cast to char* or unsigned char* for byte-wise arithmetic.
In Simple Words
A pointer stores an address.
&xgives an address,*pfollows one. Pointer arithmetic moves by whole elements, anda[i]is just*(a + i).
Initialise every pointer; use
nullptr(C++11) for "no object" and check before dereferencing.Stay inside the array (one past the end may be formed but not dereferenced).
An array decays to a pointer in most expressions, but
sizeofand assignment show they are different.Pass addresses to let a function change the caller's variables; pass
int**to change a caller's pointer.Read
constdeclarations right to left:const int*protects the value,int* constprotects the pointer.Never use a pointer after the object it points to is gone.