Defined in header <stddef.h> | ||
typedef/*implementation-defined*/ ptrdiff_t; | ||
ptrdiff_t is the signed integer type of the result ofsubtracting two pointers.
The bit width of | (since C99) (until C23) |
The bit width of | (since C23) |
Contents |
ptrdiff_t is used for pointer arithmetic and array indexing, if negative values are possible. Programs that use other types, such asint, may fail on, e.g. 64-bit systems when the index exceedsINT_MAX or if it relies on 32-bit modular arithmetic.
Only pointers to elements of the same array (including the pointer one past the end of the array) may be subtracted from each other.
If an array is so large (greater thanPTRDIFF_MAX elements, but equal to or less thanSIZE_MAX bytes), that the difference between two pointers may not be representable asptrdiff_t, the result of subtracting two such pointers is undefined.
For char arrays shorter thanPTRDIFF_MAX,ptrdiff_t acts as the signed counterpart ofsize_t: it can store the size of the array of any type and is, on most platforms, synonymous withintptr_t).
typedef typeof((int*)nullptr-(int*)nullptr) ptrdiff_t;// valid since C23 |
#include <stddef.h>#include <stdint.h>#include <stdio.h> int main(void){constsize_t N=100;int numbers[N]; printf("PTRDIFF_MAX = %ld\n",PTRDIFF_MAX);int*p1=&numbers[18],*p2=&numbers[23]; ptrdiff_t diff= p2- p1;printf("p2-p1 = %td\n", diff);}
Possible output:
PTRDIFF_MAX = 9223372036854775807p2-p1 = 5
| unsigned integer type returned by thesizeof operator (typedef)[edit] | |
| byte offset from the beginning of a struct type to specified member (function macro)[edit] | |
C++ documentation forptrdiff_t | |