首页 文章

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

提问于
浏览
-2
#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:格式'%u'需要'unsigned int'类型的参数,但参数2的类型为'struct Graph *'[-Wformat = ] |

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

2 回答

  • 4

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

    您没有数组,结构等的格式说明符 . 您必须使用单个元素/成员并根据其类型进行打印 . 您需要了解要打印的数据(类型),并使用适当的格式说明符 .

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

  • 1

    编译器是正确的, graph 有另一种类型而不是 unsigned int ,它将由 %u 打印 . 您可能想要 graph->V ,因为 struct 没有其他数字成员 .

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

    另请注意,当您尝试打印 unsigned int 时, V 具有 int 类型 .

    更新

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

    对于指针,您需要格式说明符 %p 并将其转换为它接受的类型 .

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

    online demo .

相关问题