liveBook · Manning

Ptrdiff_t

As explained in Modern C, Third Edition

ptrdiff_t is a signed integer type capable of representing the difference between pointers to elements of the same array.

ptrdiff_t is the signed integer type for differences between pointers to elements of the same array. Pointer subtraction produces this type, and the result equals the difference between the elements’ array indices. section 11.1.3

Subtracting pointers

double A[4] = { 0.0, 1.0, 2.0, -3.0 }; double* p = &A[1]; double* q = &A[3]; assert(p - q == -2); The difference is signed because q is two positions after p. Store such differences in ptrdiff_t rather than assuming that int is wide enough. section 11.1.3

Use ptrdiff_t when:

Table 5.2 Some semantic arithmetic types for specialized use cases
Type Header Context of definition Meaning
size_t <stddef.h> Type for “sizes” and cardinalities
ptrdiff_t <stddef.h> Type for size differences
uintmax_t <stdint.h> Unsigned integer type of preprocessor
intmax_t <stdint.h> Signed integer type of preprocessor
time_t <time.h> time(0), difftime(t1, t0) Calendar time in seconds since epoch
clock_t <time.h> clock() Processor time

Compare ptrdiff_t with size_t and other semantic arithmetic types, including their headers and specialized meanings. section 5.2

How Modern C, Third Edition covers it

How deep it goes
Defines the type, states the same-array constraint, gives the index-difference rule, and demonstrates subtraction without developing implementation details.
Examples
Uses two pointers into a four-element double array and verifies that subtracting their positions produces −2.
What you can do after
Evaluate pointer-position differences correctly and encode signed position or size differences with ptrdiff_t.
How it connects
Connects pointer subtraction with arrays and contrasts ptrdiff_t with size_t for unsigned object sizes.

Also explained in

Compare how 2 books explain ptrdiff_t →

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.