What is the string format for intptr_t
and uintptr_t
which is valid for both the 32 and 64 bit architecture .
EDIT
warning: format ‘%x’ expects type ‘unsigned int’, but argument 2 has type "AAA"
This is the warning i am getting in 64 bit but not in 32 bit.
intptr_t AAA
That would be the following macros from
inttypes.h
:For
printf
:PRIdPTR PRIiPTR PRIoPTR PRIuPTR PRIxPTR PRIXPTR
For
scanf
:SCNdPTR SCNiPTR SCNoPTR SCNuPTR SCNxPTR
Usage example:
%p
should work as a replacement for%x
, sinceuintptr_t
is defined to be an unsigned integer with the same size as a pointer on the platform.EDIT: Unfortunately, at least on my compiler you have to cast the variable to (void *). However, I think it is safe to cast uintptr_t to a pointer.
I'm compiling some code in an environment which for some reason does not have the
PRI.PTR
macros defined ininttypes.h
, and in whichintptr_t
is defined asint
in 32 bit andlong int
in 64 bit.I hacked around the warnings by using a
%li
format specifier and casting the variables tolong int
in theprintf
parameters. This is safe within this environment because anintptr_t
can never be longer than along int
, as described above.I wouldn't recommend using this solution if you can avoid it, but it's solved the warnings, at least.
I think even
long int
is unsafe, and you should trylong long int
, which must exist because you are working on a 64-bit architecture and you haveintptr_t
already.On some 64-bit architectures (I think Microsoft Windows would be so),
long int
may be kept in 32-bit width, to satisfy the MS-DOS-age assumption thatshort int
is always 16-bit andlong int
is always 32-bit.Even on those platforms with 32-bit
long int
,printf("%llx", (unsigned long long)AAA);
would work. And you should consider more preferrable formprintf("%jx", (uintmax_t)AAA);
if possible.Note that for some old compilers you might need to use
"%Lx"
(for GNU C, with casting tounsigned long long
) or"%I64x"
(for Visual C++, with casting to__uint64
) for 64-bit integers.P. S.
%p
may not be good in this case, because%p
may print the bareword0x
before the hexadecimals and/or may print a zero-padded value. If the both is applied, for example, the codeprintf("%p\n", (void*)16);
will print0x00000010
on 32-bit platforms and0x0000000000000010
on 64-bit platforms; the poster should have hoped just10
be printed.I think you should consider using the 'z' modifier. This will convert anything that corresponds to a size_t og ssize_t, and I have found that it works with (u)intptr_t as well.
For example:
intptr_t ip = ...; printf("ip = %zd\n", ip);