c - 指向结构体的指针的格式说明符

标签 c printf format-specifiers

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

struct Graph
{
     int v;
};

int main()
{
    struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
    graph -> v = 1;
    printf("%u", graph);
    return 0;
}

但是我收到有关行中格式的警告:

printf("%u", graph);

警告是:

/home/praveen/Dropbox/algo/c_codes/r_2e/main.c|14|warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘struct Graph *’ [-Wformat=]|

我应该对 struct Graph * 类型使用什么格式说明符?

最佳答案

C 标准仅指定预定义类型的格式说明符。扩展的宏用于打印固定宽度的整数,但不存在整个用户定义/聚合类型的格式说明符。

您没有数组、结构等的格式说明符。您必须获取单个元素/成员并根据其类型打印它们。您需要了解要打印的数据(类型)是什么,并使用适当的格式说明符。

就您而言,您可以打印成员V,其类型为int。所以你可以做类似的事情

 printf("%d", graph->V);

或者,如果您想打印 malloc() 返回的指针并存储到 graph 中,您可以这样做

  printf("%p", (void *)graph);

最后,see this discussion on why not to cast the return value of malloc() and family in C.

关于c - 指向结构体的指针的格式说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46047851/

相关文章:

c - `l` 长度修饰符对后面的 a、A、e、E、f、F、g 或 G 转换说明符没有影响

c - 程序重复出现问题

c - 如何将 char* argv[] 传递给 pthread_create?

c - 什么时候销毁 pthread 屏障是安全的?

c++ - 使用 sprintf 追加到 char 数组

bash - 如何将文本与 printf 对齐到具有非 ascii 字符的列中?

printf 中 double 的正确格式说明符

如果缓冲区在 C 中有足够的空间,则将整数复制到缓冲区

C 链表节点不存储

c - 在 C 中打印 float ,同时避免将可变参数提升为 double