Why sizeof (ptrdiff_t) == sizeof (uintptr_t)

I see several messages (e.g. size_t vs. uintptr_t ) about size_t compared to uintptr_t / ptrdiff_t, but not about the relative sizes of these new ptr p99 size types.

Machine example: vanilla ubuntu 14lts x64, gcc 4.8:

printf("%zu, %zu, %zu\n", sizeof(uintptr_t), sizeof(intptr_t), sizeof(ptrdiff_t));

Fingerprints: "8, 8, 8"

this makes no sense to me, since I would expect that the type of diff that needs to be signed requires more bits than the unsigned ptr itself.

consider:

NULL - (2^64-1)  /*largest ptr, 64bits of 1's.*/

being a 2-negative addition, would not fit in 64 bits; so I would expect ptrdiff_t to be larger than ptr_t.

[related question: why intptr_t is the same size as uintptr_t .... although it was convenient for me that it was only possible to allow the signed type to contain representation bits (for example, using signed arithmetic on negative ptr (a) be undefined and (b) have limited utility, since ptrs are by definition "positive")]

thank!

+4
source share
2 answers

-, , uintptr_t. (C ++) . , ( ). , , SIZE_MAX . , ptrdiff_t , size_t. : size_t, uintptr_t. uintptr_t , size_t. C/++ , , UINTPTR_MAX .

( , , uintptr_t size_t , , .)

NULL - (2^64-1) ( ) . , ?

-, uintptr_t size_t, , . sizeof(ptrdiff_t) sizeof(size_t) - , . , , , ptrdiff_t , , ( , SIZE_MAX ). ptrdiff_t -, size_t.

, " " undefined , . char, , SIZE_MAX * 2 / 3

char array[SIZE_MAX * 2 / 3];

undefined, ptrdiff_t , size_t

char *b = array;
char *e = array + sizeof array;

ptrdiff_t distance = e - b; // Undefined behavior!

, [ ] .

+12

, NULL (void *)0. , , . 0, . 0 , ( ). NULL ++ - 0 , . NULL .

intptr_t (uintptr_t , ) , , :

char ch;
char *cp = &ch;

assert(cp == (char *)((intptr_t)cp) );    // shall never fail

, , , , . . , . . .

size_t - max. . - , 16 , , 65535 _ char _s ( 8- !), , ).

ptrdiff_t . , 16 , 32767 char (!).

, , ptrdiff_t 24 32 , .

64- . curren 64 , 2 ** 63. , 48- , , 128- - -.

. sizeof() char, , , .

0

All Articles