This example demonstrates subtraction between pointers. When two pointers point inside the same array, subtracting them gives the number of elements between those locations.
main.c
Copy to clipboard
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
int *start = &arr[0];
int *end = &arr[4];
printf("start = %p\n", start);
printf("end = %p\n", end);
printf("Elements between pointers = %ld\n", end - start);
return 0;
}
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
int *start = &arr[0];
int *end = &arr[4];
printf("start = %p\n", start);
printf("end = %p\n", end);
printf("Elements between pointers = %ld\n", end - start);
return 0;
}
Output:
start = 0x7ffc...
end = 0x7ffc...
Elements between pointers = 4
Both pointers point to elements within the same array.
Pointer subtraction does not return the byte difference directly. Instead, it returns the number of elements between the two addresses based on the pointer type.
Since start points to arr[0] and end points to arr[4], the difference is 4.
Pointer subtraction is valid only when both pointers refer to elements of the same array.