sizeof (int) == sizeof (void*)?

后端 未结 10 878
有刺的猬
有刺的猬 2020-12-03 01:50

Is there an integer type with the same size as pointer? Guaranteed on all microarchitectures?

相关标签:
10条回答
  • 2020-12-03 02:39

    Usually sizeof(*void) depends on memory bus width (although not necessarily - pre-RISC AS/400 had 48-bit address bus but 64-bit pointers), and int usually is as big as CPU's general-purpose register (there are also exceptions - SGI C used 32-bit ints on 64-bit MIPS).

    So there is no guarantee.

    0 讨论(0)
  • 2020-12-03 02:44

    This would be true on a standard 32 bit system, but there certainly are no guarantees, and you could find lots of architectures where it isn't true. For example, a common misconception is that sizeof(int) on x86_64 would be 8 (since it's a 64 bit system, I guess), which it isn't. On x86_64, sizeof(int) is still 4, but sizeof(void*) is 8.

    0 讨论(0)
  • 2020-12-03 02:44

    The answer seems to be "no", but if all you need is a type that can act as both, you can use a union:

    union int_ptr_t {
        int i;
        void* p;
    };
    
    0 讨论(0)
  • 2020-12-03 02:48

    According to this Wikipedia page, in C99 your stdint.h header might declare intptr_t and uintptr_t, but then that of course requires

    • C99
    • A compiler implementor which has chosen to implement this optional part of the standard

    So in general I think this one is tough.

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