代码之家  ›  专栏  ›  技术社区  ›  praveen chaudhary

指向结构的指针的格式说明符

  •  -1
  • praveen chaudhary  · 技术社区  · 7 年前
    #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要求参数的类型为无符号int,但参数2的类型为struct Graph*[-Wformat=]|

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

    2 回复  |  直到 7 年前
        1
  •  5
  •   Sourav Ghosh    7 年前

    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.

        2
  •  1
  •   Melebius    7 年前

    编译器是对的, graph unsigned int %u . 你可能想要 graph->V 由于没有其他数值成员 struct

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

    还要注意您的 V int 尝试打印时键入 无符号整型

    更新

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

    %p 和它接受的类型的转换。

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

    看见 online demo .