In C, p + 1 means “the element after the one p points to”. The compiler works out how many bytes that is from the pointer’s type: 4 for a typical int, 8 for a double. Moving, comparing and subtracting pointers this way is called pointer arithmetic, and it is how C code steps through arrays and strings.
In this lesson you will learn
- How adding and subtracting whole numbers moves a pointer
- Why the step size depends on the pointer’s type
- How to loop through an array with a pointer
- What subtracting two pointers tells you
- Which pointer moves are allowed and which are not
What Pointer Arithmetic Means
A pointer holds an address. You may use four kinds of maths on it:
| Operation | Example | Result |
|---|---|---|
| Pointer + whole number | p + 3 | A pointer 3 elements further on |
| Pointer − whole number | p - 1 | A pointer 1 element back |
| Pointer − pointer | q - p | How many elements apart they are |
| Comparison | p < q | Which one comes first in the array |
You cannot add two pointers, or multiply or divide a pointer. Those would not mean anything useful.
The Step Size Follows the Type
The compiler knows what a pointer points to, so it multiplies your number by the size of that type for you.
#include <stdio.h>
int main(void) {
int nums[3] = {10, 20, 30};
double rates[3] = {1.5, 2.5, 3.5};
int *ip = nums;
double *dp = rates;
/* Measure how far "+ 1" moves each pointer, in bytes. */
printf("int pointer: ip + 1 moved %td bytes\n",
(char *)(ip + 1) - (char *)ip);
printf("double pointer: dp + 1 moved %td bytes\n",
(char *)(dp + 1) - (char *)dp);
printf("*(ip + 2) = %d, same as nums[2] = %d\n", *(ip + 2), nums[2]);
printf("*(dp + 1) = %.1f, same as rates[1] = %.1f\n", *(dp + 1), rates[1]);
return 0;
}
Output
int pointer: ip + 1 moved 4 bytes
double pointer: dp + 1 moved 8 bytes
*(ip + 2) = 30, same as nums[2] = 30
*(dp + 1) = 2.5, same as rates[1] = 2.5
Both pointers moved by “1”, yet the int pointer moved 4 bytes and the double pointer moved 8. (The exact sizes can differ on unusual systems, but the rule does not.) The program casts to char * only to measure the gap in bytes, because a char is always 1 byte.
This also explains array indexing. In C, nums[i] is defined to mean *(nums + i). Indexing is pointer arithmetic with nicer spelling.
Walking Through an Array
A pointer can replace the index in a loop. You start at the first element and stop when the pointer reaches the end.
#include <stdio.h>
int main(void) {
int data[] = {5, 9, 2, 7, 4};
int *start = data;
int *end = data + 5; /* one past the last element: allowed */
int sum = 0;
for (int *p = start; p < end; p++) {
sum += *p;
}
printf("sum = %d\n", sum);
int *seven = &data[3];
printf("7 is at index %td\n", seven - start); /* pointer difference */
printf("elements after it: %td\n", end - seven - 1);
return 0;
}
Output
sum = 27
7 is at index 3
elements after it: 1
Two details matter here:
data + 5points one past the last element. C allows you to make this pointer and compare with it, but not to read through it. It is the natural “stop here” marker.seven - startsubtracts two pointers into the same array. The answer is a count of elements, not bytes. Its type isptrdiff_t, printed with%td.
Two Classic Uses
Many standard tasks use pointer arithmetic. Here is a home-made strlen and an in-place reverse that moves two pointers toward each other:
#include <stdio.h>
/* Count characters with pointer arithmetic, like strlen. */
size_t my_strlen(const char *s) {
const char *p = s;
while (*p != '\0') p++;
return (size_t)(p - s);
}
/* Reverse an array in place using two pointers. */
void reverse(int *left, int *right) {
while (left < right) {
int tmp = *left;
*left++ = *right;
*right-- = tmp;
}
}
int main(void) {
printf("length of \"pointer\" = %zu\n", my_strlen("pointer"));
int a[] = {1, 2, 3, 4, 5, 6};
reverse(a, a + 5);
for (int i = 0; i < 6; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}
Output
length of "pointer" = 7
6 5 4 3 2 1
In *left++ = *right; the value is copied first, and then left moves on. The loop stops when the two pointers meet in the middle. The same idea appears in many array problems, such as reversing an array.
Going Past the End of an Array
Pointer arithmetic is only defined inside one array, plus the single position just after it. Breaking this rule is undefined behaviour, even if the program seems to work.
- Reading the one-past-the-end element.
*(data + 5)in a five-element array reads memory that is not yours. - Moving before the start.
data - 1is not a valid pointer, even if you never read through it. - Subtracting pointers from different arrays. The answer means nothing.
- Arithmetic on
void *. Standard C does not allow it, becausevoidhas no size. GCC allows it as an extension, which hides the problem. Cast tochar *or the real type first. - Mixing up
*p++and(*p)++. The first moves the pointer; the second adds 1 to the value it points at. See operator precedence.
Practice Exercises
Exercise 1. If short is 2 bytes and short *s holds address 1000, what address does s + 4 hold?
Show answer
1000 + 4 × 2 = 1008.
Exercise 2. With int a[10]; int *p = &a[2], *q = &a[9];, what is q - p?
Show answer
7. Pointer subtraction counts elements, not bytes.
Exercise 3. Rewrite for (int i = 0; i < n; i++) total += a[i]; using a pointer instead of i.
Show answer
for (const int *p = a; p < a + n; p++) total += *p;
Frequently Asked Questions
Is pointer arithmetic faster than array indexing?
Usually not today. a[i] and *(a + i) mean the same thing, and modern compilers produce the same machine code for both. Choose whichever is clearer.
Why can I point one past the end of an array?
The C standard allows it so loops can use an end marker, as in p < a + n. You may compare with that pointer, but you must not read or write through it.
Can I do arithmetic on a void pointer?
Not in standard C, because void has no size. Convert it to char * to move byte by byte, or to the real type to move element by element.
What type does subtracting two pointers give?
A signed integer of type ptrdiff_t, defined in stddef.h. Print it with %td.
Summary
p + nmoves a pointer bynelements; the byte step is set by the type.a[i]is the same as*(a + i).- Subtracting two pointers into one array gives the number of elements between them.
- Stay inside the array; only one-past-the-end may be formed, and never read.
- No arithmetic on
void *in standard C.
