Why / when to use `intptr_t` for type-casting in C?

前端 未结 4 1226
长发绾君心
长发绾君心 2020-11-28 03:13

I have a question regarding using intptr_t vs. long int. I\'ve observed that incrementing memory addresses (e.g. via manual pointer arithmetic) dif

相关标签:
4条回答
  • 2020-11-28 03:50

    Here's the thing: on some platforms, int is the right size, but on others, long is the right size. How do you know which one is the one you should use? You don't. One might be right, but the standard makes no guarantees about which one it would be (if it is either). So the standard provides a type that is defined to be the correct size, regardless of what platform you're on. Where before you had to write:

    #ifdef PLATFORM_A
      typedef long intptr;
    #else
      typedef int intptr;
    #endif
    

    Now you just write:

    #include <stdint.h>
    

    And it covers so many more cases. Imagine specializing the snippet above for every single platform your code runs on.

    0 讨论(0)
  • 2020-11-28 03:57

    You could make your life easier by using the p conversion specifier:

    printf("%p\n", (void *)foo);
    

    Also, the portable way to print a variable of type (u)intptr_t is to use the PRI*PTR macros from inttypes.h; the following is equivalent to using p on my platform (32-bit):

    printf("%08" PRIxPTR "\n", (uintptr_t)(void *)foo);
    

    The casts to void * are necessary for full portability, but can be omitted on platforms with uniform pointer representations.

    0 讨论(0)
  • 2020-11-28 04:02

    intptr_t is a new invention, created after 64-bit and even 128-bit memory addresses were imagined.

    If you ever need to cast a pointer into an integer type, always use intptr_t. Doing anything else will cause unnecessary problems for people who need to port your code in the future.

    It took a long time to iron out all of the bugs with this in programs like Mozilla/Firefox when people wanted to compile it on 64-bit Linux.

    0 讨论(0)
  • 2020-11-28 04:15

    First, intptr_t is only for data pointers (not functions) and is not guaranteed to exist.

    Then, no, you shouldn't use it for the purpose of printing. The %p is for that. You just have to cast your pointer to (void*) and there you go.

    It is also no good for arithmetic / accessing individual bytes. Cast to (unsigned char*) instead.

    intptr_t is really for the rare occasions that you have to interpret pointers as integers (which they really aren't). Don't that if you mustn't.

    0 讨论(0)
提交回复
热议问题