Char * a, * b; what type (ba) and how to print it?

{
  char *a, *b;

  printf("%lx\n",(b-a));
}

Usually it works, in fact, I can’t imagine that it would give a warning or fail on a 32-bit or 64-bit machine. But is this what you need to do for ANSI C and to understand the size? I would like this code to work on every possible platform, including non-Unix and embedded systems.

+5
source share
5 answers

b - a- this ptrdiff_tis which you can print with %tdin format printf. From spec 6.5.6 Additive Operators:

, ; . , ( ) ptrdiff_t, <stddef.h>.

printf , 7.19.6. /:

t , d, i, o u, x x, ptrdiff_t ; n ptrdiff_t.

spec , , , ptrdiff_t, undefined:

J.2 Undefined
- ptrdiff_t (6.5.6).

- , . , PTRDIFF_MIN PTRDIFF_MAX <stdint.h> .

+22

b - a , a b char. a b, , , char.

undefined. undefined.

, ptrdiff_t. ptrdiff_t - typedef typedef. , .

, C , ptrdiff_t , , . ptrdiff_t , undefined.

printf ptrdiff_t C99, , ,

printf("%ld\n", (long) (b - a));

: C99 ptrdiff_t. C99

printf("%td\n", b - a);

, t . d, o, u, x x , , . C89/90 .

P.S.. , , 32- 64- . , ( ) . , ptrdiff_t 32- 32-. , 31 . , (.. 32 "" ), b - a . , 33- ptrdiff_t 32- 65- ptrdiff_t 64- . , , , "" undefined .

+12

ptrdiff_t. man stddef.h:

ptrdiff_t
              Signed integer type of the result of subtracting two pointers.

%td.

+5

a b, undefined. b-a ptrdiff_t, , . C, % tx.

% tx, , ( ) :

printf("%lx", (unsigned long)(a-b));

It is possible that the system may have, for example, a 32-bit address space, and a 32-bit ptrdiff_t, but a 64-bit length, and then your printf will fail.

+2
source

Type ba ptrdiff_t

+2
source

All Articles