Printf指针以十进制表示法

3 c printf pointers

如何以十进制表示法打印指针?

编译时,以下都不会产生所需的结果-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;
}
Run Code Online (Sandbox Code Playgroud)

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

Bjo*_* A. 7

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;
}
Run Code Online (Sandbox Code Playgroud)

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

intptr_t和uintptr_t的字符串格式似乎也是相关的.