如何打印十进制的指针?
使用 -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 有一个名为 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 会发出警告。
关于c - 十进制的printf指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39674122/