These are the notes for C episode 10. In episode 7 a function tried to add a tip to main's bill and failed, because it only got a photocopy. Here you fix that for real by inventing pointers: you will learn that every variable has an address, how to print it with %p, how to store it in a pointer (int *p = &bill;), how to go to that address with *p (dereferencing), pass by address (and why scanf needs &), the classic pointer swap, what happens when you forget the & or use the wrong pointer type, NULL and the segmentation fault, and why an array's name is an address. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run as shown.
Addresses change on every run. The operating system places your program somewhere new each time it starts, so the
0x7ffd...numbers you see will be different from the ones printed here. What stays the same is the relationship: two things that share an address always print the same number.
The problem: the tip that vanished
Remember episode 7? main has a bill of 100. A function add_tip adds ten rupees:
#include <stdio.h>
void add_tip(int bill) {
bill = bill + 10;
}
int main() {
int bill = 100;
add_tip(bill);
printf("In main: %d\n", bill);
return 0;
}
Output:
In main: 100
The tip vanished. C passes arguments by value: the parameter bill inside add_tip is a brand-new variable holding a copy of 100. The function changed the copy, and the copy was thrown away when the function ended.
Why: a copy can't lead you back home
- The function only ever sees a copy.
- A copy can't lead you back to the original... but a location can.
- So instead of sending what's inside
bill, send wherebilllives. Then the function can go there and change the real thing.
That raises the question: does a variable even have a location?
Every variable has an address
Real-life example: houses on a street. Think of memory as a long street of houses.
| On your street | In C |
|---|---|
| A house, people live inside | A variable, its value lives inside: int bill = 100; |
| Its house number | Its address: &bill |
| Delivery uses the number, not the people | %p prints an address |
Every variable is stored somewhere in memory, and that place has a number: its address. The & operator (the address-of operator) asks "what's the address?". You have already used it in scanf("%d", &x). To print an address, printf uses %p (we cast to (void *), the type %p expects):
#include <stdio.h>
int main() {
int bill = 100;
printf("bill = %d\n", bill);
printf("bill lives at: %p\n", (void *)&bill);
return 0;
}
Output (one example run):
bill = 100
bill lives at: 0x7ffd8bfea304
The long number is written in hexadecimal (base 16, digits 0-9 and a-f), and the 0x prefix marks it as hexadecimal. It changes every run.
A pointer: an address written on a chit
Real-life example: an address on a chit.
| In real life | In C |
|---|---|
| A chit with an address: "House 42" | int *p = &bill; p stores bill's address |
| Go to that house, follow the chit | *p: the value at that address |
| Repaint the house: the real house changes | *p = 150; bill becomes 150 |
An address is just a number, so it can be stored in a variable. A variable that stores an address is called a pointer.
int *p = &bill;declarespas a pointer to an int and storesbill's address in it. The*in a declaration means "this is a pointer".*pin an expression means "go to the address inpand use the value there". This is called dereferencing.- Assigning to
*pchanges the variable that lives at that address.
#include <stdio.h>
int main() {
int bill = 100;
int *p = &bill;
printf("bill lives at: %p\n", (void *)&bill);
printf("p holds: %p\n", (void *)p);
printf("*p = %d\n", *p);
*p = 150;
printf("bill = %d\n", bill);
printf("sizeof(p) = %zu\n", sizeof(p));
return 0;
}
Output (one example run):
bill lives at: 0x7ffd610d0c44
p holds: 0x7ffd610d0c44
*p = 100
bill = 150
sizeof(p) = 8
pholds exactlybill's address.*pis 100, the value living there.*p = 150;changedbillwithout ever writingbill =.- A pointer takes 8 bytes on a 64-bit machine: every address is 8 bytes, whatever type it points to.
Two symbols, two meanings
int bill = 100;
int *p = &bill;
| You write | Read it as |
|---|---|
&bill |
"the address of bill" |
int *p |
"p is a pointer to an int" (declaration) |
*p |
"go to the address in p, use the value" (dereference) |
*&bill |
& and * undo each other: it's just bill |
The fix: pass the address
Now add_tip takes an address (int *bill) and changes the value at that address. main sends the address with &:
#include <stdio.h>
void add_tip(int *bill) {
*bill = *bill + 10;
}
int main() {
int bill = 100;
add_tip(&bill);
printf("In main: %d\n", bill);
return 0;
}
Output:
In main: 110
The function changed main's bill because it had the address, not a photocopy. This is called pass by address (often called "pass by reference" in C tutorials; strictly, C still passes the address by value). You just invented pointers.
And now you know why scanf needs &. scanf("%d", &x) has to store a number in your variable, so it needs your variable's address. Without the &, it would only get a copy of the (garbage) value.
Forgetting the &
The most common pointer mistake: the function expects an address, but we send the value.
#include <stdio.h>
void add_tip(int *bill) {
*bill = *bill + 10;
}
int main() {
int bill = 100;
add_tip(bill);
printf("In main: %d\n", bill);
return 0;
}
gcc warns:
main.c: In function 'main':
main.c:9:13: warning: passing argument 1 of 'add_tip' makes pointer from integer without a cast [-Wint-conversion]
9 | add_tip(bill);
| ^~~~
| |
| int
main.c:3:19: note: expected 'int *' but argument is of type 'int'
3 | void add_tip(int *bill) {
| ~~~~~^~~~
It still compiles, and running it prints:
Segmentation fault
The function treated 100 as a house number and walked to a part of memory that doesn't belong to the program. A segmentation fault is the operating system stopping a program for touching memory it may not use. Note that In main: was never printed. Treat every pointer warning as an error.
Swap two bills
The waiter put the bills on the wrong tables: table 1 has 250, table 2 has 90. First, a swap the way we'd have written it before today (using a temporary variable t, like swapping two glasses with a third, empty glass):
#include <stdio.h>
void swap(int a, int b) {
int t = a;
a = b;
b = t;
}
int main() {
int table1 = 250, table2 = 90;
swap(table1, table2);
printf("Table 1: %d, Table 2: %d\n", table1, table2);
return 0;
}
Output:
Table 1: 250, Table 2: 90
Nothing swapped: the function swapped two photocopies. With addresses:
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int main() {
int table1 = 250, table2 = 90;
swap(&table1, &table2);
printf("Table 1: %d, Table 2: %d\n", table1, table2);
return 0;
}
Output:
Table 1: 90, Table 2: 250
Rule: to let a function change a variable, pass its address.
Pointing somewhere else
A pointer is a variable too, so it can be given a new address. Think of a waiter's chit: it says "table 1", he adds a tip there, then rubs it out and writes "table 2". No star changes the chit (where p points); a star changes the house (the value at that address).
#include <stdio.h>
int main() {
int table1 = 250, table2 = 90;
int *p = &table1;
*p = *p + 10;
p = &table2;
*p = *p + 10;
printf("Table 1: %d, Table 2: %d\n", table1, table2);
return 0;
}
Output:
Table 1: 260, Table 2: 100
Forget the & (p = table2;) and gcc warns, then the program crashes, because p now holds the number 90 as if it were an address:
main.c: In function 'main':
main.c:7:7: warning: assignment to 'int *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
7 | p = table2;
| ^
Segmentation fault
The pointer's type matters
price is a float, but we store its address in an int pointer:
#include <stdio.h>
int main() {
float price = 12.5;
int *p = &price;
printf("%d\n", *p);
return 0;
}
gcc warns:
main.c: In function 'main':
main.c:5:14: warning: initialization of 'int *' from incompatible pointer type 'float *' [-Wincompatible-pointer-types]
5 | int *p = &price;
| ^
Output:
1095237632
Not 12.5. A pointer's type tells C how to read the bytes at the address. The 4 bytes of the float 12.5 read as an int give the meaningless number 1095237632. A float's address goes in a float *, an int's address in an int *.
NULL: a chit with no address
Real-life example: a blank chit.
| In real life | In C |
|---|---|
| A blank chit, no address yet | int *p = NULL; points nowhere |
| Drive to "nowhere": you can't | *p = 5; Segmentation fault |
| Check the chit first | if (p != NULL) then use *p |
NULL is a special pointer value meaning "no address". Dereferencing it crashes:
#include <stdio.h>
int main() {
int *p = NULL;
*p = 5;
printf("Saved\n");
return 0;
}
Output:
Segmentation fault
Saved was never printed. Check before you go:
#include <stdio.h>
int main() {
int *p = NULL;
if (p != NULL) {
*p = 5;
printf("Saved\n");
} else {
printf("No address yet!\n");
}
return 0;
}
Output:
No address yet!
Even worse: a pointer with no value at all
A pointer you declare without initialising (int *p;) holds a random leftover address, a wild pointer. Writing through it is undefined behavior:
#include <stdio.h>
int main() {
int *p;
*p = 5;
printf("%d\n", *p);
return 0;
}
On our machine this printed Segmentation fault, with no warning from gcc at this level. On another run or machine it might silently overwrite some other variable instead, which is worse. Always start a pointer with an address or with NULL.
Arrays are addresses
Real-life example: the train's platform number.
| At the station | In C |
|---|---|
| "Platform 3": where the first coach is | bills = &bills[0] |
| Tell a friend the platform: they board the real train | total(bills, 5): the function gets an address |
| No need to ask "where?", you already said it | scanf("%s", name): name is already an address |
Used in an expression, an array's name gives the address of its first slot:
#include <stdio.h>
int main() {
int bills[3] = {120, 45, 80};
printf("bills = %p\n", (void *)bills);
printf("&bills[0] = %p\n", (void *)&bills[0]);
int *p = bills;
printf("*p = %d\n", *p);
return 0;
}
Output (one example run):
bills = 0x7ffd877a7808
&bills[0] = 0x7ffd877a7808
*p = 120
The same address twice, and *p is the first bill. This solves two mysteries from earlier episodes:
- Episode 8: passing
billsto a function passed an address, so the function could changemain's array, andsizeof(bills)inside the function measured an 8-byte address instead of the whole array. - Episode 9:
scanf("%s", name)needs no&becausenameis already an address.
Moving p from coach to coach (p + 1, p + 2) is pointer arithmetic, the topic of the next episode.
Common mistakes (and the real gcc messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
add_tip(bill); when it wants int * |
warning: passing argument 1 of 'add_tip' makes pointer from integer without a cast, then Segmentation fault |
Sent the value, not the address | add_tip(&bill); |
int *p = &price; (price is float) |
warning: initialization of 'int *' from incompatible pointer type 'float *', junk output |
The type says how to read the bytes | float *p = &price; |
int *p = NULL; *p = 5; |
Segmentation fault |
NULL points nowhere | if (p != NULL) { ... } |
int *p; *p = 5; |
Segmentation fault (or silent damage) |
p holds a random address | int *p = &x; or int *p = NULL; |
printf("%d", p) to print an address |
warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' and a wrong number |
%d is for ints |
printf("%p", (void *)p) |
Confusing *p = 5 with p = 5 |
warning: assignment to 'int *' from 'int' makes pointer from integer without a cast |
*p is the value, p is the address |
Use *p to change the value |
Mini project: two answers from one function
A function can return only one value, but at closing time bhaiya wants two: the total and the biggest bill. With pointers, a function can hand back as many answers as we like: the caller passes the addresses where the answers should go.
#include <stdio.h>
void summary(int bills[], int n, int *total, int *biggest) {
*total = 0; *biggest = bills[0];
for (int i = 0; i < n; i++) {
*total = *total + bills[i];
if (bills[i] > *biggest) *biggest = bills[i];
}
}
int main() {
int bills[5];
for (int i = 0; i < 5; i++) scanf("%d", &bills[i]);
int total, biggest;
summary(bills, 5, &total, &biggest);
printf("Total: Rs %d\n", total);
printf("Biggest: Rs %d\n", biggest);
return 0;
}
Input:
120 45 80 200 60
Output:
Total: Rs 505
Biggest: Rs 200
scanfgets&bills[i], the address of each slot.totalandbiggeststart empty inmain;summarywrites its answers straight into them through*totaland*biggest.- Pointer parameters used this way are often called output parameters.
Practice
- Write
void double_it(int *n)that doublesmain's number. - Swap two
floats with pointers. - Write
void min_max(int a[], int n, int *mn, int *mx). - Print the addresses of three
intvariables. What do you notice?
Solutions and hints
All four in one program (verified):
#include <stdio.h>
void double_it(int *n) {
*n = *n * 2;
}
void swap_f(float *a, float *b) {
float t = *a;
*a = *b;
*b = t;
}
void min_max(int a[], int n, int *mn, int *mx) {
*mn = a[0];
*mx = a[0];
for (int i = 1; i < n; i++) {
if (a[i] < *mn) *mn = a[i];
if (a[i] > *mx) *mx = a[i];
}
}
int main() {
int n = 21;
double_it(&n);
printf("Doubled: %d\n", n);
float chai = 15.5, lassi = 40.25;
swap_f(&chai, &lassi);
printf("chai = %.2f, lassi = %.2f\n", chai, lassi);
int bills[5] = {120, 45, 80, 200, 60};
int lo, hi;
min_max(bills, 5, &lo, &hi);
printf("Smallest: %d, Biggest: %d\n", lo, hi);
int x = 1, y = 2, z = 3;
printf("&x = %p\n&y = %p\n&z = %p\n", (void *)&x, (void *)&y, (void *)&z);
return 0;
}
Output (one example run):
Doubled: 42
chai = 40.25, lassi = 15.50
Smallest: 45, Biggest: 200
&x = 0x7ffecd926724
&y = 0x7ffecd926728
&z = 0x7ffecd92672c
4. The addresses are close together and differ by 4: each int takes 4 bytes. (The compiler decides the order, so on your machine they may be in a different order or not perfectly next to each other; never rely on it.)
Quick quiz
What does this print?
int x = 5;
int *p = &x;
*p = *p * 2;
x = x + 1;
printf("%d %d", x, *p);
- A.
10 10 - B.
11 10 - C.
11 11 - D.
6 10
Answer
C: 11 11. p points at x, so *p = *p * 2 makes x 10. Then x becomes 11. *p just reads x's house, so it is 11 too. (Verified output: 11 11.)
Interview questions
- What is a pointer? What is the difference between
p,*pand&p? - What do
&and*mean in a declaration versus an expression? - How can a C function change a variable of its caller?
- Why does
scanfneed&xfor anintbut not for achararray? - Write a function that swaps two integers. Why doesn't
swap(int a, int b)work? - What is a
NULLpointer? What is a wild (uninitialised) pointer? - What is a segmentation fault?
- What is the size of a pointer on a 64-bit system? Does it depend on the type it points to?
- How can a function "return" more than one value in C?
- What is the relationship between an array's name and a pointer?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Memory | The computer's storage for a running program, a long row of numbered bytes | where bill lives |
| Address | The number of the place in memory where a variable is stored | 0x7ffd8bfea304 |
& (address-of) |
Gives the address of a variable | &bill |
%p |
printf format for printing an address (pass a void *) |
printf("%p", (void *)&bill) |
| Hexadecimal | Base-16 numbers, digits 0-9 and a-f; 0x marks them |
0x7ffd... |
| Pointer | A variable that stores an address | int *p = &bill; |
| Pointer type | The type of value a pointer points to; it tells C how to read the bytes there | int *, float * |
Dereference (*) |
Go to the address in a pointer and use the value there | *p = 150; |
| Pass by value | The function gets a copy of the argument | add_tip(int bill) can't change main's bill |
| Pass by address | The function gets the address, so it can change the original | add_tip(&bill) |
| Output parameter | A pointer parameter a function writes an answer into | int *total in summary |
NULL |
A special pointer value meaning "points nowhere" | int *p = NULL; |
| Segmentation fault | The OS stopping a program that touched memory it may not use | dereferencing NULL |
| Wild (uninitialised) pointer | A pointer that was never given an address; it holds a random one | int *p; *p = 5; |
| Undefined behavior | Code whose result C doesn't promise: a crash, junk, or seeming to work | writing through a wild pointer |
(void *) |
A "pointer to anything"; the type %p expects |
(void *)p |
| Array name as address | In an expression, an array's name is the address of slot 0 | bills == &bills[0] |
| Pointer arithmetic | Moving a pointer by whole elements (p + 1) |
next episode |
Summary
- Every variable has an address:
&x, printed with%p. It changes from run to run. - A pointer stores an address:
int *p = &x;.*pgoes to that address to read or changex. - Pass the address and a function can change the caller's variable:
add_tip(&bill),swap(&a, &b). That's whyscanfneeds&. - Forgetting
&or using the wrong pointer type gives warnings, then crashes or junk: treat pointer warnings as errors. NULLmeans "no address"; checkp != NULLbefore*p. Never use an uninitialised pointer.- An array's name is the address of its first slot, which is why functions can change arrays and
%sneeds no&.
Next episode: Pointers 2. Our pointer stands at coach 0 of the train; next time it learns to walk: p + 1, p + 2, pointer arithmetic, and how arrays and pointers are secretly the same thing.