The ISO C standards provide this typedef (defined in stddef.h). ptrdiff_t is a signed integer typedef which is guaranteed to be able to store the difference between two pointers. Note that you do not know that ptrdiff_t will be an int; for instance, on SGI's 64 bit memory model, ints are 4 bytes, while pointers are 8.

Even more perplexing is the fact that you cannot really rely on the sign of the difference! For instance, on a machine with 32 bit pointers and 32 bit ints, we might have

typedef int ptrdiff_t;
In such a situation, if (DANGER! Non-portable code ahead!)
char *p = (char*) 0x11111111;
char *q = (char*) 0x99999999;
then p<q, but p-q will be a positive int.

ptrdiff_t is far from perfect. But used with care, it can help make some things portable which couldn't be without it.

Log in or register to write something here or to contact authors.