These are the notes for C episode 11. In episode 10 our pointer was standing at coach 0 of the bills train. Here you teach it to walk: you will see why p + 4 is not "4 bytes further", learn pointer arithmetic (a pointer counts in elements), walk an array with p++, discover that a[i] is just *(a + i), see why an array is still not a pointer (sizeof, bills++), meet the silent "one past the end" bug, subtract pointers to get an index, write your own strlen, and reverse an array in place with two pointers. 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
0x7ffc...numbers will be different on your machine. What stays the same is the distance between two addresses.
The problem: reaching coach 1
Here is the train from episode 10: five bills, and a pointer p standing at coach 0.
| Coach (index) | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Bill (Rs) | 120 | 45 | 80 | 200 | 60 |
We want coach 1. Thinking like engineers: "an int takes 4 bytes, so coach 1 starts 4 bytes later. Add 4."
#include <stdio.h>
int main() {
int bills[5] = {120, 45, 80, 200, 60};
int *p = bills;
printf("coach 0: %d\n", *p);
printf("coach 1: %d\n", *(p + 4));
return 0;
}
Output:
coach 0: 120
coach 1: 60
No error, no warning, and a wrong answer: 60 is the bill in coach 4. We jumped four whole coaches, not four bytes.
p + 1 counts in elements
Real-life example: "two coaches ahead", not "46 metres ahead".
| On the platform | In C |
|---|---|
| "Go 2 coaches ahead": nobody counts metres | p + 2 = 2 elements ahead |
| The guard knows how long a coach is | C knows an int is 4 bytes (from the pointer's type) |
| A bus is shorter than a coach: "1 bus ahead" is fewer metres | char *s: s + 1 is just 1 byte further |
Pointer arithmetic means adding to or subtracting from a pointer. In C, p + n means "n elements after p". The compiler multiplies by the element size for you:
bytes moved = n × sizeof(element)
So p + 4 was 4 ints = 16 bytes further: coach 4. To reach coach 1 you simply write p + 1.
#include <stdio.h>
int main() {
int bills[5] = {120, 45, 80, 200, 60};
int *p = bills;
printf("p = %p\n", (void *)p);
printf("p + 1 = %p\n", (void *)(p + 1));
printf("*(p + 1) = %d\n", *(p + 1));
printf("*(p + 2) = %d\n", *(p + 2));
return 0;
}
Output (one example run):
p = 0x7ffca367f9d0
p + 1 = 0x7ffca367f9d4
*(p + 1) = 45
*(p + 2) = 80
The two addresses differ by exactly 4 (...d0 → ...d4): one step of an int * is 4 bytes.
The type decides the step size
Same + 1 on three types. Casting both pointers to char * and subtracting measures the distance in bytes:
#include <stdio.h>
int main() {
char c[2]; int i[2]; double d[2];
printf("char: %td byte\n", (char *)(c + 1) - (char *)c);
printf("int: %td bytes\n", (char *)(i + 1) - (char *)i);
printf("double: %td bytes\n", (char *)(d + 1) - (char *)d);
return 0;
}
Output:
char: 1 byte
int: 4 bytes
double: 8 bytes
| Pointer type | p + 1 moves |
Why |
|---|---|---|
char * |
1 byte | sizeof(char) is 1 |
int * |
4 bytes | sizeof(int) is 4 on this machine |
double * |
8 bytes | sizeof(double) is 8 |
This is one more reason (after episode 10) that a pointer's type matters.
What you can do with pointer arithmetic
| Expression | Meaning |
|---|---|
p + n, p - n |
The address n elements after / before p |
*(p + n) |
The value n elements after p |
p++, p-- |
Move p itself one element forward / back |
p += n |
Move p n elements forward |
q - p |
How many elements lie between them (both in the same array) |
p < q, p == q |
Compare positions in the same array |
p + q |
Not allowed: adding two addresses means nothing |
Walk the train with p++
Real-life example: the ticket checker. He gets on at coach 0 (p = bills), collects the bill (total += *p), walks to the next coach (p++), and gets off after the last coach (p < bills + 5).
bills + 5 is the position just after the last coach. It is a fine address to compare against, as long as you never dereference it.
#include <stdio.h>
int main() {
int bills[5] = {120, 45, 80, 200, 60};
int total = 0;
for (int *p = bills; p < bills + 5; p++) {
total = total + *p;
}
printf("Total: Rs %d\n", total);
return 0;
}
Output:
Total: Rs 505
No index, no square brackets: a pointer walking from coach to coach. This "start / p < end / p++" shape is the standard way to walk an array with a pointer.
*p++ vs (*p)++
Not in the video, but you will see it in real code. *p++ means "use *p, then move p". (*p)++ means "add 1 to the value at p":
#include <stdio.h>
int main() {
int bills[5] = {120, 45, 80, 200, 60};
int *p = bills;
printf("%d\n", *p++);
printf("%d\n", *p);
printf("%d\n", (*p)++);
printf("%d\n", bills[1]);
return 0;
}
Output:
120
45
45
46
When in doubt, write it in two lines (total += *p; p++;). Clear beats clever.
The secret of a[i]
Put the pieces together:
bills(the array's name) is the address of coach 0 (episode 10).bills + 2is the address of coach 2 (pointer arithmetic).*(bills + 2)goes there and reads it.
So bills[2] and *(bills + 2) are the same thing. In fact the C standard defines square brackets this way: a[i] is *(a + i). That is also why indexes start at 0: the first element is zero elements away from the start.
#include <stdio.h>
int main() {
int bills[5] = {120, 45, 80, 200, 60};
int *p = bills;
printf("%d %d\n", bills[2], *(bills + 2));
printf("%d %d\n", p[2], *(p + 2));
printf("%d\n", 2[bills]);
return 0;
}
Output:
80 80
80 80
80
- Square brackets work on a pointer too:
p[2]is 80. 2[bills]becomes*(2 + bills), and addition doesn't care about order, so it also prints 80. It's a famous interview trick; never write it in real code.
An array is not a pointer
Real-life example: the train vs a chit with its platform number.
| At the station | In C |
|---|---|
| The train itself: 5 coaches of steel | int bills[5]: holds all 5 ints, sizeof = 20 |
| A chit saying "Platform 3" | int *p = bills;: holds one address, sizeof = 8 |
| You can rewrite a chit, you can't move the station | p++ is fine, bills++ is an error |
#include <stdio.h>
int main() {
int bills[5] = {120, 45, 80, 200, 60};
int *p = bills;
printf("sizeof(bills) = %zu\n", sizeof(bills));
printf("sizeof(p) = %zu\n", sizeof(p));
return 0;
}
Output:
sizeof(bills) = 20
sizeof(p) = 8
Now try to move both:
p++;
bills++;
gcc says:
main.c: In function 'main':
main.c:9:10: error: lvalue required as increment operand
9 | bills++;
| ^~
An lvalue is something that can appear on the left of =: a place in memory you are allowed to change (like a variable). An array's name is a fixed address, not a variable, so it can't be incremented or assigned to.
In most expressions an array's name decays (turns into) a pointer to its first element. The exceptions you have met: sizeof(array) (gives the whole array's size) and &array. That decay is why, inside a function, an array parameter is really a pointer and sizeof gives 8 (episode 8).
One coach too far
Change < to <=:
#include <stdio.h>
int main() {
int bills[5] = {120, 45, 80, 200, 60};
int total = 0;
for (int *p = bills; p <= bills + 5; p++) {
total = total + *p;
}
printf("Total: Rs %d\n", total);
return 0;
}
Output (one example run; the number changes from machine to machine):
Total: Rs 33272
No error and no warning: the loop also read *(bills + 5), whatever memory sits right after the array. C never checks array bounds for you. Reading or writing past the end is undefined behaviour: a junk value, a crash, or silently damaged data.
Rule: the "end" pointer (
a + n) is for comparing only. Never dereference it.
Subtracting pointers
Real-life example: "Which coach is the passenger in?" Walk until you find him, then count coaches from the engine.
Subtracting two pointers into the same array gives the number of elements between them (again, not bytes). The result has type ptrdiff_t and printf prints it with %td.
#include <stdio.h>
int main() {
int bills[5] = {120, 45, 80, 200, 60};
int *p = bills;
while (*p != 200) {
p++;
}
printf("Found 200 at coach %td\n", p - bills);
return 0;
}
Output:
Found 200 at coach 3
(Careful: this loop assumes 200 is in the array. If it isn't, p walks off the end. A safe version also checks p < bills + 5.)
Printing the difference with %d gives:
warning: format '%d' expects argument of type 'int', but argument 2 has type 'long int' [-Wformat=]
Strings: a train of chars
From episode 9: a string is an array of char that ends with the null character '\0'. A char * moves 1 byte per step, so walk it until it sits on '\0', then subtract the start: that's the length. This is how strlen works inside.
#include <stdio.h>
int my_strlen(char *s) {
char *start = s;
while (*s != '\0') {
s++;
}
return s - start;
}
int main() {
char name[] = "Rajdhani";
printf("%d\n", my_strlen(name));
return 0;
}
Output:
8
Common mistakes (and the real gcc messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
*(p + 4) to reach the next int ("4 bytes") |
No error: prints coach 4 (60) |
p + n moves n elements, not bytes |
*(p + 1) |
bills++; |
error: lvalue required as increment operand |
An array name is a fixed address | int *p = bills; p++; |
p <= bills + 5 |
No error: a junk total | bills + 5 is past the last element |
p < bills + 5 |
printf("%d", p - bills); |
warning: format '%d' expects argument of type 'int', but argument 2 has type 'long int' |
p - q has type ptrdiff_t |
printf("%td", p - bills); |
while (*p != 200) p++; when 200 isn't there |
Walks off the end: junk or a crash | No end check | while (p < end && *p != 200) |
| Subtracting pointers from two different arrays | No error, meaningless number | Only valid inside one array | Subtract only within the same array |
Mini project: reverse the train
The train must run backwards, so reverse the coaches in place (no second array). Two workers start at the two ends, swap their coaches, and step towards the middle until they meet. This two-pointer technique is an interview favourite.
#include <stdio.h>
void reverse(int *left, int *right) {
while (left < right) {
int t = *left;
*left = *right;
*right = t;
left++;
right--;
}
}
int main() {
int coaches[6];
for (int i = 0; i < 6; i++) scanf("%d", &coaches[i]);
reverse(coaches, coaches + 5);
for (int *p = coaches; p < coaches + 6; p++) printf("%d ", *p);
printf("\n");
return 0;
}
Input:
1 2 3 4 5 6
Output:
6 5 4 3 2 1
coaches + 5 is the last coach (index 5), not the end pointer. With an odd number of coaches (say 7) the middle coach meets itself and left < right stops before touching it: input 1 2 3 4 5 6 7 gives 7 6 5 4 3 2 1. It takes n/2 swaps.
Practice
- Find the biggest bill with a walking pointer, and print which coach it's in.
- Write
int count(char *s, char c)that counts how many timescappears, using acharpointer. - Copy one array into another using two pointers.
- Check whether a word is a palindrome (reads the same backwards) with
leftandrightpointers.
Solutions
All four in one program (verified):
#include <stdio.h>
int count(char *s, char c) {
int n = 0;
for (; *s != '\0'; s++)
if (*s == c) n++;
return n;
}
void copy(int *src, int *dst, int n) {
for (int *end = src + n; src < end; src++, dst++)
*dst = *src;
}
int is_palindrome(char *s) {
char *left = s, *right = s;
while (*right != '\0') right++;
right--; /* last real letter */
while (left < right) {
if (*left != *right) return 0;
left++;
right--;
}
return 1;
}
int main() {
int bills[5] = {120, 45, 80, 200, 60};
int *big = bills;
for (int *p = bills + 1; p < bills + 5; p++)
if (*p > *big) big = p;
printf("Biggest: %d at coach %td\n", *big, big - bills);
printf("a in Rajdhani: %d\n", count("Rajdhani", 'a'));
int backup[5];
copy(bills, backup, 5);
for (int *p = backup; p < backup + 5; p++) printf("%d ", *p);
printf("\n");
printf("level: %d, chai: %d\n", is_palindrome("level"), is_palindrome("chai"));
return 0;
}
Output:
Biggest: 200 at coach 3
a in Rajdhani: 2
120 45 80 200 60
level: 1, chai: 0
Quick quiz
What does this print?
int a[] = {10, 20, 30, 40};
int *p = a + 1;
printf("%d %d", *p + 1, *(p + 1));
- A.
21 30 - B.
11 20 - C.
20 30 - D.
21 21
Answer
A: 21 30. p points at 20. *p + 1 reads 20, then adds 1 → 21. *(p + 1) moves to the next element first, then reads → 30. (Verified output: 21 30.)
Interview questions
- What does
p + 1do for anint *, achar *and adouble *? - Why is
a[i]equivalent to*(a + i)? Why doesi[a]compile? - What is the difference between an array and a pointer? Give two examples where they behave differently.
- What does "array decays to a pointer" mean?
- Why does
arr++fail butp++work? - What is the type of
p - q? When is pointer subtraction valid? - Can you add two pointers? Why not?
- What happens if you read one element past the end of an array?
- Implement
strlenusing pointers. - Reverse an array in place using two pointers. What is its time complexity?
- What is the difference between
*p++and(*p)++?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Pointer arithmetic | Adding to, subtracting from, or comparing pointers; steps are in elements | p + 1, p++, q - p |
| Element | One item of an array | bills[3] is one element |
| Step size | How many bytes p + 1 moves: sizeof of the pointed-to type |
4 for int * |
p++ |
Move the pointer to the next element | walking an array |
| End pointer | The address just after the last element, used only for comparing | bills + 5 |
a[i] |
Defined as *(a + i) |
bills[2] = *(bills + 2) |
| Array decay | An array's name turning into a pointer to its first element in an expression | passing bills to a function |
| lvalue | Something that can be on the left of =: a changeable place in memory |
a variable x, *p, bills[1] |
ptrdiff_t |
The type of the difference between two pointers | p - bills |
%td |
printf format for a ptrdiff_t |
printf("%td", p - bills) |
| Undefined behaviour | Code the C standard gives no meaning to; anything can happen | reading bills[5] |
| Null character | '\0', the end marker of a C string |
"Rajdhani" ends with it |
| Two-pointer technique | Two pointers moving through an array (often towards each other) | reversing, palindrome check |
| In place | Changing the data where it is, without a second copy | reverse above |
Summary
p + nmoves n elements, not n bytes; the pointer's type sets the step (1, 4, 8 bytes...).- Walk an array with
for (p = a; p < a + n; p++). a[i]is just*(a + i), which is why indexes start at 0.- An array is not a pointer: it holds all its elements (
sizeof20 vs 8) and its name can't move (lvalue required). a + nis the end: compare with it, never dereference it. Going past the end gives no warning.q - pis the number of elements between them; print it with%td.strlenis acharpointer walking to'\0'; two pointers can reverse an array in place.
Next episode: Structures: keep a student's name, roll number and marks together in one box.