0 day streak
c / expert
Snippet

Pointer Subtraction and ptrdiff_t

The result of subtracting two pointers is of the signed integer type 'ptrdiff_t'. This operation is only defined if both pointers point to elements within the same array or one past the last element. Subtracting pointers to different types (like char *) allows calculating the exact byte distance between memory addresses.

snippet.c
c
1
2
3
4
5
6
7
8
#include <stddef.h>
int buffer[1024];
int *start = &buffer[10];
int *end = &buffer[100];
ptrdiff_t offset = end - start;
size_t bytes = (char *)end - (char *)start;
Breakdown
1
ptrdiff_t offset = end - start;
Calculates the number of 'int' elements between the two pointers (result is 90).
2
(char *)end - (char *)start
Casting to char* ensures the subtraction reflects the distance in bytes rather than element count.