string format for intptr_t and uintptr_t

26,822

Solution 1

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:

uintptr_t p = SOME_VALUE;
printf("Here's a pointer for you: %" PRIxPTR "\n", p);

Solution 2

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);

Share:
26,822
thetna
Author by

thetna

I am a guy from Nepal who is very much fond of doing programming.

Updated on May 03, 2020

Comments

  • thetna
    thetna about 4 years

    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
    
  • Fred Foo
    Fred Foo about 13 years
    Usage example: uinptr_t p = SOME_VALUE; printf("Here's a pointer for you: %" PRIxPTR "\n", p);
  • thetna
    thetna about 13 years
    Thanks for your answer ,my question may not be so precise... what exactly i intend to know if there any strong format like "%d" for integer and so on. I am getting some warning depending upon the hardware architecture.I have edited my question.
  • Stargateur
    Stargateur over 6 years
    sorry but this question is tagged with C so why answer with a cpp solution ?
  • ZHOU Ling
    ZHOU Ling over 6 years
    using '#include <typeinfo>' need cpp suffix. As far as I know, printf is C function, not CPP funtion, std::printf is CPP funtion.
  • ZHOU Ling
    ZHOU Ling over 6 years
    @Stargateur You said this is a cpp solution, just because there is a cpp suffix?
  • Stargateur
    Stargateur over 6 years
    typeid don't exist in C, sooooooo.
  • ZHOU Ling
    ZHOU Ling over 6 years
    Added a __Generic version for C.
  • ZHOU Ling
    ZHOU Ling over 6 years
    test.{cpp|c} simply for proving intptr_t is the same as ptrdiff_t, ptrdiff_t has standard string format %t(man 3 printf). so intptr_t has string format %td, uintptr_t has string format %tu. I think I have answered the question. Anyway, I don't want to waste time in this question any more.
  • Antti Haapala -- Слава Україні
    Antti Haapala -- Слава Україні over 3 years
    Congratulations, you have found undefined behaviour.
  • dxiv
    dxiv over 2 years
    @AnttiHaapala Would void *p = ...; printf("%td", (ptrdiff_t)p); be (the same kind of) UB?