These are the notes for C++ episode 9. Pointers are the topic people fear most in C++, but you won't memorise a single rule here. A swap function that refuses to swap leads you to memory addresses and the & operator, then to the pointer (a variable that stores an address) and dereferencing with *. You will fix the swap, discover the secret link between pointers and arrays (and why sizeof gives 8 inside a function), crash a program with a null pointer and then make it safe with nullptr checks, and finally return two answers from one function. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; the outputs and error messages are copied from those runs.
About addresses in the outputs: a printed address (like
0x7ffc17637e04) is different on your machine and usually changes on every run, because the operating system chooses where your variables live. The addresses below are examples from our runs. Everything else in the outputs is exact.
The problem: Ravi's and Priya's marks, typed the wrong way round
Rao ma'am's helper typed the marks into the register: Ravi 65, Priya 92. But they were the wrong way round: Ravi actually scored 92, and Priya 65. Easy, you think: write a function swapMarks that swaps two numbers.
| Step | What happened |
|---|---|
| The marks are entered | Ravi 65 · Priya 92 typed into the register |
| The two marks are swapped | Ravi really got 92, Priya 65 |
| Write a swap function | swapMarks(ravi, priya) to fix it |
| Nothing changed | it swapped photocopies (episode 7 again) |
The failing attempt: a swap that doesn't swap
A classic swap: keep a in temp, put b into a, put temp into b.
#include <iostream>
using namespace std;
void swapMarks(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int ravi = 65, priya = 92;
swapMarks(ravi, priya);
cout << "Ravi: " << ravi << ", Priya: " << priya << endl;
return 0;
}
Output:
Ravi: 65, Priya: 92
Nothing changed. No error, no warning.
Why it fails: pass by value (the photocopy)
Remember episode 7: functions get copies. a and b were photocopies of ravi and priya. The function swapped the copies perfectly, and then threw them away when it ended. main's variables were never touched.
But in episode 8, addGrace did change main's array. Why? Because it didn't get a copy of the array; it got the array's address (where it lives in memory). So the idea is: what if we could hand a function the address of Ravi's mark, so it can go there and change the real thing?
Fix, part 1: every variable has an address
| In a housing society | In memory | Meaning |
|---|---|---|
| Hundreds of flats, all in one society | RAM: billions of bytes | Memory is one long row of tiny boxes |
| Flat B-204: every flat has a number | 0x7ffd...: every byte has an address |
A number for every box |
| Ravi lives in B-204 (the family vs the flat number) | marks = 78 lives at &marks |
What's inside (value) vs where it is (address) |
Your computer's memory is like a huge housing society with billions of tiny flats called bytes. Every flat has a number; in memory that number is called an address. When you write int marks = 78;, the value 78 moves into some flat. So there are two different things: the value inside, and the address of the flat. The & symbol (ampersand), written before a variable, gives you its address. This is the address-of operator.
#include <iostream>
using namespace std;
int main() {
int marks = 78;
cout << "Value: " << marks << endl;
cout << "Address: " << &marks << endl;
return 0;
}
Output (the address is an example; yours will differ):
Value: 78
Address: 0x7ffc17637e04
The address starts with 0x, which means it is written in hexadecimal: a base-16 way of writing numbers (digits 0-9 and letters a-f), the usual way addresses are shown. Your address will be different and can change on every run, because the operating system picks the flat. What matters is: every variable has one.
Fix, part 2: a pointer stores an address
| On a delivery app | In C++ | Meaning |
|---|---|---|
| You share a location pin (not the house, just where it is) | int* p = &marks; |
p stores an address: a pointer |
| The rider follows the pin and reaches the real house | *p |
go to that address: dereference |
| He drops the parcel inside; the real house changes | *p = 90; |
marks becomes 90 |
A pointer is a variable that stores an address instead of a normal value. Like a location pin on a delivery app: it isn't the house, it's where the house is. A star * before a pointer means "go to that address"; this is called dereferencing. And whatever the rider drops off lands in the real house: *p = 90 changes the real variable.
#include <iostream>
using namespace std;
int main() {
int marks = 78;
int* p = &marks;
cout << "p holds: " << p << endl;
cout << "*p is: " << *p << endl;
*p = 90;
cout << "marks is now: " << marks << endl;
return 0;
}
Output (the address is an example):
p holds: 0x7ffe16947dd4
*p is: 78
marks is now: 90
Read int* p = &marks; right to left: "p is a pointer to an int, and it holds the address of marks". *p is 78: follow the pin and read what's in the house. And marks is now 90, though we never wrote marks = 90. We changed it through the pointer.
Two symbols, two jobs
p marks
[ 0x7ffd...a4 ] ---> [ 78 ] at 0x7ffd...a4
p holds the address of marks, so we draw an arrow from p to marks. That's why it's called a pointer: it points at something.
| Symbol | Where | Meaning | Example |
|---|---|---|---|
& |
before a variable | "the address of" | &marks |
* |
in a declaration | "pointer to" | int* p = p is a pointer to an int |
* |
anywhere else, before a pointer | "the value at that address" | *p, *p = 90 |
How big is a pointer itself? It holds an address, not an int, so its size is the size of an address: 8 bytes on a 64-bit machine like ours.
#include <iostream>
using namespace std;
int main() {
int marks = 78;
int* p = &marks;
cout << "sizeof(int): " << sizeof(int) << endl;
cout << "sizeof(p): " << sizeof(p) << endl;
cout << "&marks == p: " << (&marks == p) << endl;
return 0;
}
Output:
sizeof(int): 4
sizeof(p): 8
&marks == p: 1
(1 means true: p holds exactly the address of marks.)
The pointer's type must match
An int* must hold the address of an int. A double's address can't go into an int pointer:
#include <iostream>
using namespace std;
int main() {
double price = 60.5;
int* p = &price;
return 0;
}
main.cpp: In function 'int main()':
main.cpp:6:14: error: cannot convert 'double*' to 'int*' in initialization
6 | int* p = &price;
| ^~~~~~
| |
| double*
Why so strict? An int pointer reads 4 bytes and treats them as an int; a double is 8 bytes stored in a completely different format. Reading it as an int would give nonsense, so C++ refuses. Fix: double* p = &price;.
Fix, part 3: a swap that works
Now the parameters are int* a and int* b: two location pins. Inside, *a and *b go to the real houses. Keep Ravi's mark in temp, move Priya's into Ravi's house, then temp into Priya's. And main sends the addresses: &ravi, &priya.
#include <iostream>
using namespace std;
void swapMarks(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int ravi = 65, priya = 92;
swapMarks(&ravi, &priya);
cout << "Ravi: " << ravi << ", Priya: " << priya << endl;
return 0;
}
Output:
Ravi: 92, Priya: 65
Fixed! The function didn't get photocopies. It got the addresses (the pointers themselves are still copied, but a copy of a pin leads to the same house), and changed the real variables. This is often called pass by pointer (or pass by address).
A common slip: forgetting the & in the call. Change line 12 to swapMarks(ravi, priya);:
main.cpp: In function 'int main()':
main.cpp:12:15: error: invalid conversion from 'int' to 'int*' [-fpermissive]
12 | swapMarks(ravi, priya);
| ^~~~
| |
| int
main.cpp:4:21: note: initializing argument 1 of 'void swapMarks(int*, int*)'
4 | void swapMarks(int* a, int* b) {
| ~~~~~^
main.cpp:12:21: error: invalid conversion from 'int' to 'int*' [-fpermissive]
12 | swapMarks(ravi, priya);
| ^~~~~
| |
| int
main.cpp:4:29: note: initializing argument 2 of 'void swapMarks(int*, int*)'
4 | void swapMarks(int* a, int* b) {
| ~~~~~^
The function wants addresses, and we passed plain numbers. A mark is not a location. (One error per argument. [-fpermissive] is just the name of a g++ option that would loosen this rule; don't use it, fix the call.)
Pointers and arrays: the address of the first coach
| At the station | In C++ | Meaning |
|---|---|---|
| "Coach 0 is at pillar 12": where the train starts | marks is the same as &marks[0] |
the array name is an address |
| Next coach = one coach further (not one step) | p + 1 |
4 bytes on: the next int |
| Two coaches from the start is coach 2 | *(p + 2) is the same as marks[2] |
[i] is pointer maths |
Here's the secret behind episode 8. An array's name, used on its own, is the address of its first slot. Add 1 to a pointer, and C++ moves one whole slot, not one byte; for an int that's 4 bytes further. This is called pointer arithmetic. So *(p + 2) is the value two slots ahead: marks[2]. In fact, square brackets are just a shortcut for this pointer maths.
#include <iostream>
using namespace std;
int main() {
int marks[5] = {78, 92, 65, 88, 71};
int* p = marks;
cout << p << endl;
cout << p + 1 << endl;
cout << *(p + 2) << " = " << marks[2] << endl;
return 0;
}
Output (the addresses are examples; the gap between them is always 4):
0x7fffbba66040
0x7fffbba66044
65 = 65
int* p = marks; needs no &: the array's name already is an address. The two addresses are exactly 4 apart (…40 to …44), because one int is 4 bytes. And *(p + 2) is 65, the same as marks[2].
Why the size had to be passed separately (episode 8's mystery)
#include <iostream>
using namespace std;
void show(int m[]) {
cout << "Inside: " << sizeof(m) << endl;
}
int main() {
int marks[5] = {78, 92, 65, 88, 71};
cout << "In main: " << sizeof(marks) << endl;
show(marks);
return 0;
}
g++ compiles it, but warns:
main.cpp: In function 'void show(int*)':
main.cpp:5:34: warning: 'sizeof' on array function parameter 'm' will return size of 'int*' [-Wsizeof-array-argument]
5 | cout << "Inside: " << sizeof(m) << endl;
| ~^~
main.cpp:4:15: note: declared here
4 | void show(int m[]) {
| ~~~~^~~
Output:
In main: 20
Inside: 8
In main, sizeof(marks) is 20 bytes: five ints of 4 bytes. Inside the function it's 8. Look at the first line of the warning: g++ itself calls the function void show(int*). The function never received the array; it received a pointer to slot 0, which is 8 bytes on this machine. It knows where the train starts, but not how long it is. So you always pass the size along with an array.
The next problem: a pointer to nowhere (nullptr)
| Step | Delivery app | C++ |
|---|---|---|
| No pin yet | the customer hasn't chosen a location | a pointer that points nowhere |
| Deliberately empty | "no address" | int* p = nullptr; |
| Ride to nowhere | the rider sets off anyway | *p on nullptr |
| Check the pin first | look before you go | if (p != nullptr) |
Sometimes a pointer has nowhere to point yet. C++ says that clearly with nullptr: a special value meaning "this pointer points to nothing". But what if the rider sets off anyway?
#include <iostream>
using namespace std;
int main() {
int* p = nullptr;
cout << "Before" << endl;
cout << *p << endl;
cout << "After" << endl;
return 0;
}
Output:
Before
Segmentation fault
The program crashed, and After never printed. The operating system stopped it for touching memory it doesn't own; that crash is called a segmentation fault (segfault). Note: this compiled fine. g++ can't always know where a pointer points, so this is a runtime crash, not a compile error.
The fix: check the pin first.
#include <iostream>
using namespace std;
int main() {
int* p = nullptr;
if (p != nullptr) {
cout << *p << endl;
} else {
cout << "p points nowhere" << endl;
}
return 0;
}
Output:
p points nowhere
No crash. And always give a pointer a starting value: an address, or nullptr. An uninitialised pointer (int* p;) holds a random leftover address, which is even worse than null: you can't even test it, because it doesn't look empty.
Common mistakes (and the real g++ messages)
| Mistake | Code | What g++ says / what happens | Fix |
|---|---|---|---|
Forgetting & when a function wants an address |
swapMarks(ravi, priya); with swapMarks(int*, int*) |
error: invalid conversion from 'int' to 'int*' [-fpermissive] |
swapMarks(&ravi, &priya); |
| Pointer of the wrong type | double price = 60.5; int* p = &price; |
error: cannot convert 'double*' to 'int*' in initialization |
double* p = &price; |
| Dereferencing a null pointer | int* p = nullptr; cout << *p; |
compiles; at run time: Segmentation fault |
if (p != nullptr) before *p |
sizeof on an array parameter |
sizeof(m) inside void show(int m[]) |
warning: 'sizeof' on array function parameter 'm' will return size of 'int*' [-Wsizeof-array-argument]; prints 8, not 20 |
pass the size: show(marks, 5) |
| Storing a plain number in a pointer | int* p = 5; |
error: invalid conversion from 'int' to 'int*' [-fpermissive] |
int* p = &marks; |
Forgetting * when changing the value |
p = 90; (meant the value) |
error: invalid conversion from 'int' to 'int*' [-fpermissive] |
*p = 90; |
Thinking int* p, q; makes two pointers |
int* p, q; then q = &priya; |
error: invalid conversion from 'int*' to 'int' [-fpermissive] (the * belongs to p only; q is a plain int) |
int *p, *q; or one per line |
Using * on something that isn't a pointer |
int marks = 78; cout << *marks; |
error: invalid type argument of unary '*' (have 'int') |
cout << marks; (or use a pointer) |
| Taking the address of a plain number | int* p = &78; |
error: lvalue required as unary '&' operand (78 has no flat of its own) |
store it in a variable first, then use & |
| Uninitialised pointer | int* p; *p = 90; |
compiles without a warning; undefined behaviour: our run crashed with Segmentation fault |
start every pointer with an address or nullptr |
| Returning the address of a local variable | int* makeMarks() { int marks = 78; return &marks; } |
warning: address of local variable 'marks' returned [-Wreturn-local-addr]; our run then crashed with Segmentation fault |
the local dies when the function returns; return the value instead (int) |
Mini project: lowest and highest from one function
Rao ma'am wants the lowest and the highest mark, from one function. Problem: return can hand back only one value.
| Step | What happens |
|---|---|
| Highest mark? And the lowest too | Rao ma'am wants both |
return gives ONE value |
return is a one-way, one-value door |
| Send two empty boxes' pins | main passes &lowest, &highest |
| The function fills them | both answers arrive, no return needed |
Pointers solve it: main makes two empty variables and sends their addresses. The function writes both answers straight into main's variables. These are sometimes called output parameters.
#include <iostream>
using namespace std;
void minMax(int m[], int n, int* lo, int* hi) {
*lo = m[0];
*hi = m[0];
for (int i = 1; i < n; i++) {
if (m[i] < *lo) *lo = m[i];
if (m[i] > *hi) *hi = m[i];
}
}
int main() {
int marks[5] = {78, 92, 65, 88, 71};
int lowest, highest;
minMax(marks, 5, &lowest, &highest);
cout << "Lowest: " << lowest << endl;
cout << "Highest: " << highest << endl;
return 0;
}
Output:
Lowest: 65
Highest: 92
minMaxtakes the array, its sizen(remember: the function can't work out the size itself), and twointpointers,loandhi.- Both start at the first mark,
m[0]. Then the loop walks the rest: a mark smaller than*lobecomes the new lowest; a mark bigger than*hibecomes the new highest. - Two answers from one function, delivered through two pointers.
- Try it: add the average as a third pointer parameter,
double* avg.
Practice
- Write
void doubleIt(int* x)and test it. - Print an array using only a pointer and
p++. - Write
void divide(int a, int b, int* q, int* r)for quotient and remainder. - Predict, then run:
int* p = nullptr; if (p) cout << *p;
Solution
1. *x = *x * 2 goes to the real variable and doubles it.
#include <iostream>
using namespace std;
void doubleIt(int* x) {
*x = *x * 2;
}
int main() {
int marks = 45;
doubleIt(&marks);
cout << "After doubling: " << marks << endl;
doubleIt(&marks);
cout << "Again: " << marks << endl;
return 0;
}
After doubling: 90
Again: 180
2. p starts at slot 0; end is the address just past the last slot (marks + 5). p++ moves p one whole int forward each time.
#include <iostream>
using namespace std;
int main() {
int marks[5] = {78, 92, 65, 88, 71};
int* p = marks;
int* end = marks + 5;
while (p < end) {
cout << *p << " ";
p++;
}
cout << endl;
return 0;
}
78 92 65 88 71
(end is only compared with, never dereferenced: slot 5 doesn't exist.)
3. 17 laddoos shared among 5 kids: quotient through q, remainder through r.
#include <iostream>
using namespace std;
void divide(int a, int b, int* q, int* r) {
*q = a / b;
*r = a % b;
}
int main() {
int laddoos = 17, kids = 5;
int each, left;
divide(laddoos, kids, &each, &left);
cout << "Each kid gets: " << each << endl;
cout << "Left over: " << left << endl;
return 0;
}
Each kid gets: 3
Left over: 2
4. Prediction: it prints nothing and does not crash. In a condition, a pointer counts as false when it is nullptr and true otherwise, so if (p) means the same as if (p != nullptr). The *p is skipped. Verified: this program's output is empty, and it exits normally.
#include <iostream>
using namespace std;
int main() {
int* p = nullptr;
if (p) cout << *p;
return 0;
}
To see that it really finished, add a line after the if:
#include <iostream>
using namespace std;
int main() {
int* p = nullptr;
if (p) cout << *p;
cout << "Done, no crash" << endl;
return 0;
}
Done, no crash
Quick quiz
What does this print?
int a = 5;
int* p = &a;
*p = *p + 10;
cout << a << endl;
- A.
5 - B.
15 - C. An address like
0x7ffd... - D. Compile error
Answer
B: 15 (verified). p holds the address of a. *p = *p + 10 reads a (5), adds 10, and writes 15 back into a itself. So a is 15.
Interview questions
- What is a pointer? A variable that stores the memory address of another variable.
int* p = &x;makesppoint tox. - What do
&and*mean?&xis the address ofx. In a declaration,int* pmeans "p is a pointer to int"; elsewhere,*pdereferences: it means the value at the address inp. - Why doesn't
void swap(int a, int b)swap the caller's variables? Pass by value:aandbare copies. To change the originals, pass their addresses (int*) or use references (int&, episode 10). - What is the relationship between arrays and pointers? An array's name, in most expressions, converts to a pointer to its first element:
marksequals&marks[0], andmarks[i]is the same as*(marks + i). - What is pointer arithmetic? Adding an integer to a pointer moves it by that many elements, not bytes: for
int* p,p + 1is 4 bytes further (with 4-byte ints). - Why is
sizeofof an array parameter 8? An array parameterint m[]is reallyint* m, sosizeof(m)is the size of a pointer (8 bytes on a 64-bit system). That's why the size must be passed separately. - What is
nullptr, and why use it overNULLor 0? A null pointer constant of its own type (std::nullptr_t) meaning "points to nothing". UnlikeNULL/0 it can't be mistaken for an integer, e.g. in overloaded functions. - What is a segmentation fault? A crash raised by the operating system when a program accesses memory it isn't allowed to, e.g. dereferencing
nullptr. It happens at run time; the code usually compiles fine. - What is a dangling or wild pointer? A wild pointer is uninitialised and holds a random address. A dangling pointer points to memory that no longer exists, e.g. the address of a local variable after its function returned. Using either is undefined behaviour.
- How can a function "return" more than one value? Pass addresses of the caller's variables as output parameters (
minMax(marks, 5, &lowest, &highest)), or use references, a struct, orstd::pair.
Glossary
| Term | Plain meaning | Example |
|---|---|---|
| Memory (RAM) | The computer's working storage: one huge row of tiny boxes holding your program's data | where marks lives while the program runs |
| Byte | One tiny box of memory; an int takes 4 of them |
sizeof(int) is 4 |
| Address | The number of a byte in memory, like a flat number | 0x7ffc17637e04 (example) |
| Hexadecimal | Base-16 numbers using 0-9 and a-f; addresses are printed this way, starting with 0x |
0x7ffc... |
Address-of operator (&) |
Gives the address of a variable | &marks |
| Pointer | A variable that stores an address | int* p |
int* |
The type "pointer to int": holds the address of an int |
int* p = &marks; |
Dereference (*) |
Go to the address a pointer holds and use the value there | *p is 78; *p = 90; |
| Point to / points at | A pointer "points to" the variable whose address it holds | p points to marks |
| Pass by value | The function gets a copy; the caller's variable is unchanged | swapMarks(int a, int b) |
| Pass by pointer (address) | The function gets the address, so it can change the caller's variable | swapMarks(&ravi, &priya) |
| Parameter / argument | The variable in the function's definition / the value passed in the call | int* a / &ravi |
| Output parameter | A pointer parameter the function writes its answer into | int* lo, int* hi in minMax |
| Array | Many values of one type in a row, numbered from 0 (episode 8) | int marks[5] |
| Slot / element / index | One value in an array / that value / its position number | marks[2] is 65 |
| Array name as a pointer | Used alone, an array's name is the address of slot 0 | int* p = marks; |
| Pointer arithmetic | Adding to a pointer moves it by whole elements, not bytes | p + 1 is the next int |
p++ |
Moves the pointer to the next element | walk an array with a pointer |
sizeof |
Gives the size of a type or variable in bytes | sizeof(marks) is 20 |
| Array parameter | int m[] in a function's parameter list; it is really int* m |
void show(int m[]) |
nullptr |
A special pointer value meaning "points to nothing" | int* p = nullptr; |
| Null pointer | A pointer holding nullptr |
p before you give it an address |
| Null check | Testing a pointer before dereferencing it | if (p != nullptr) or if (p) |
| Segmentation fault | A crash: the operating system stops a program that touches memory it doesn't own | *p when p is nullptr |
| Runtime error / crash | A failure while the program runs, after it compiled fine | the segfault above |
| Compile error | A mistake g++ finds before the program runs; no program is produced | cannot convert 'double*' to 'int*' |
| Warning | g++ compiles the program but points out something suspicious | 'sizeof' on array function parameter ... |
| Uninitialised (wild) pointer | A pointer given no starting value; it holds a random address | int* p; |
| Dangling pointer | A pointer to memory that no longer exists | address of a local returned from a function |
| Local variable | A variable inside a function; it disappears when the function returns (episode 7) | int marks inside makeMarks |
| Undefined behaviour | Code whose result C++ doesn't define: it may work, print garbage or crash | dereferencing an uninitialised pointer |
| lvalue | Something with its own place in memory that & can take the address of |
marks is one; 78 is not |
[-fpermissive] |
Name of a g++ option shown in some errors; it would relax the rule, but you should fix the code | invalid conversion ... [-fpermissive] |
| Operating system | The software (Linux, Windows) that runs programs and hands out memory | it picks each variable's address |
| Reference | Another name for an existing variable (next episode) | int& r = marks; |
Summary
- A swap with
int a, int bswaps copies (pass by value), so the caller sees no change. - Every variable lives at an address;
&xgives it. Addresses print in hexadecimal and change between runs. - A pointer stores an address:
int* p = &x;.*pfollows it to the real value, so*p = 90changesx. - Pass addresses (
swapMarks(&ravi, &priya)) to let a function change your variables; forgetting&givesinvalid conversion from 'int' to 'int*'. - The pointer's type must match:
cannot convert 'double*' to 'int*'. - An array's name is the address of slot 0;
p + 1is the next slot (4 bytes on for anint);*(p + 2)ismarks[2]. - Array parameters are really pointers, so
sizeofgives 8 inside a function: always pass the size. nullptrmeans "points nowhere";*pon it is a Segmentation fault at run time. Check first, and always initialise pointers.returngives one value; pointers let one function hand back several (minMax).
Next episode: references and dynamic memory. Pointers work, but all those stars and ampersands get messy. Next time: references, the cleaner C++ way to share a variable, and dynamic memory with new and delete.