【问题标题】:Printf pointer in decimal notation十进制的printf指针
【发布时间】:2016-09-24 08:14:27
【问题描述】:

如何打印十进制的指针?

使用-Wall 编译时,以下都不会产生所需的结果。我了解这些错误,并且确实想使用-Wall 进行编译。但是,我怎样才能打印十进制的指针呢?

#include <stdio.h>
#include <stdlib.h>

int main() {
    int* ptr = malloc(sizeof(int));
    printf("%p\n", ptr);                 // Hexadecimal notation
    printf("%u\n", ptr);                 // -Wformat: %u expects unsigned int, has int *
    printf("%u\n", (unsigned int) ptr);  // -Wpointer-to-int-cast
    return EXIT_SUCCESS;
}

(这是必需的,因为我在点图中使用指针作为节点标识符,而0x.. 不是有效标识符。)

【问题讨论】:

    标签: c pointers printf


    【解决方案1】:

    C 有一个名为 uintptr_t 的数据类型,它大到足以容纳一个指针。一种解决方案是将指针转换(转换)为 (uintptr_t) 并如下所示打印:

    #include <stdio.h>
    #include <stdlib.h>
    #include <inttypes.h>
    
    int main(void) 
    {
        int* ptr = malloc(sizeof *ptr);
        printf("%p\n", (void *)ptr);                 // Hexadecimal notation
        printf("%" PRIuPTR "\n", (uintptr_t)ptr);
        return EXIT_SUCCESS;
    }
    

    请注意,%p 需要一个 void* 指针,如果您使用 -pedantic 编译代码,gcc 会发出警告。

    string format for intptr_t and uintptr_t 似乎也相关。

    【讨论】:

      【解决方案2】:

      有报告称“某些”平台未在其 inttypes.h 文件中提供 PRI*PTR 宏。如果是您的情况,请改用printf("%ju\n", (uintmax_t)ptr);

      ...虽然我认为您应该拥有这些宏,因为您看起来正在使用 GNU C。

      【讨论】:

        猜你喜欢
        • 2014-11-20
        • 1970-01-01
        • 2020-08-14
        • 2013-01-11
        • 2013-01-21
        • 1970-01-01
        • 1970-01-01
        • 2015-12-09
        • 1970-01-01
        相关资源
        最近更新 更多