c - 十进制的printf指针

标签 c pointers printf

如何打印十进制的指针?

使用 -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 会发出警告。

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

关于c - 十进制的printf指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39674122/

相关文章:

c - 什么 ABI(如果有的话)限制 [u]intmax_t 的大小?

合并两个共享 (.so) 库

c - 为什么下面的 C 代码出现段错误?

c - 我应该使用 #include <file.h> 还是 "file.h"?

c++ - (c++) 检查指针数组的空值

C - fprintf() & printf() 删除数组元素内存

c - 指针并置使得 int_pointer 指向字符数据,反之亦然

c++ - 用c++创建的动态数组

mysql - 在另一个函数中使用 asprintf 为字符串分配内存

c - Typedef 结构返回的值与 C 中存储的值不同