【问题标题】:Format specifier for a pointer to a structure指向结构的指针的格式说明符
【发布时间】:2018-02-13 07:54:08
【问题描述】:
#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|警告:格式'%u'需要'unsigned int'类型的参数,但参数2的类型为'struct Graph *' [-格式=]|

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

【问题讨论】:

  • 文档说什么是正确的格式说明符?
  • struct Graph * 类型没有格式说明符。在您指定要打印的内容之前,这个问题毫无意义。指针中存储的地址?还是别的什么?
  • printf("%u", graph); --> printf("%p", (void *)graph);
  • 你期望什么输出?

标签: c printf format-specifiers


【解决方案1】:

编译器是对的,graph 具有不同于unsigned int 的另一个类型,它将由%u 打印。您可能想要graph-&gt;V,因为struct 没有其他数字成员。

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

在您尝试打印unsigned int 时,还要注意您的V 具有int 类型。

更新

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

对于指针,您需要格式说明符 %p 和对其接受的类型的强制转换。

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

online demo

【讨论】:

  • If you want to print the address of the pointer, you need to cast it to an (unsigned) int. --> 我的反对票。检查文档。
  • 你为什么要把指针指向unsigned int?在许多平台上,指针比unsigned int 大得多。这样的演员阵容有什么意义?它的结果意味着什么?
  • @AnT @AnT int 不是平台原生字的大小等于指针的大小吗?
  • @Melebius:不一定(尽管这确实是意图)。您想要一个与指针宽度相同的整数类型——即uintptr_tintptr_tunsigned int 在大多数现实生活平台上固定为 32 位宽度,而指针可以轻松拥有 64 位宽度。
  • p 仅针对 void-pointer 定义。所以打印它的值的代码应该是:printf("%p", (void*) graph);
【解决方案2】:

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

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

在您的情况下,您可以打印成员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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2012-03-28
    • 1970-01-01
    相关资源
    最近更新 更多