Subtracting two pointers
What you'll learn: How to find the number of elements between two memory addresses using pointer subtraction.
The "Distance" Concept
In previous lessons, we learned that adding to a pointer moves it forward in memory. But what happens when you subtract one pointer from another?
Imagine a row of identical lockers in a hallway. If you are standing at locker #10 and your friend is at locker #4, you don't say you are "six yards" apart; you say you are "six lockers" apart. Pointer subtraction works exactly like this. Instead of giving you the raw number of bytes between two addresses, C tells you how many elements (lockers) fit between them.
How it Works in Code
When you subtract two pointers of the same type, C automatically handles the math based on the size of the data type. If you subtract two int pointers, the result is the number of integers between them, not the number of bytes.
#include <stdio.h>
int main() {
int measurements[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int *start = &measurements[0]; // Point to the first element
int *end = &measurements[7]; // Point to the eighth element
// Subtracting the start from the end
long distance = end - start;
printf("The distance is %ld elements.\n", distance);
// Output: The distance is 7 elements.
return 0;
}
Why This Matters
Pointer subtraction is most commonly used to calculate the length of a string or a specific segment of an array. Because C doesn't always track how large an array is, you can find the size of a "slice" of data simply by subtracting the pointer at the beginning from the pointer at the end.
There are two important rules to remember:
- Same Array Only: Subtraction only makes sense if both pointers point into the same array. Subtracting a pointer for a "High Scores" list from a pointer for a "Username" string will result in unpredictable, meaningless numbers.
- The Result Type: The result of this operation is an integer type called
ptrdiff_t. It’s essentially a signed integer that is large enough to hold the distance between any two pointers on your specific computer.
Key takeaway
Subtracting two pointers tells you the number of elements between them, not the number of bytes.