【问题标题】:Unexpected compiler warning意外的编译器警告
【发布时间】:2018-03-03 17:43:03
【问题描述】:

如何删除此警告?

warning: format '%d' expects argument of type ' int', but argument 2 has type 'int *' [-Wformat=] printf(“%d”,p1->j);

这是代码,除了警告之外一切正常。

void main()
{
    struct s1
    {
        int *j;
    };

    struct s2
    {
        int k;
    };
    struct s1 *p1;
    struct s2 *p2;

    p1=malloc(sizeof(struct s1));
    p2=malloc(sizeof(struct s2));
    p2->k=5;
    p1->j=&p2->k;
    printf("%d",p1->j);
}

【问题讨论】:

  • printf("%d",p1->j);->printf("%d",*(p1->j));
  • 是一些学习指针练习的代码吗?因为它没有任何其他意义。
  • 你真的应该能够在没有外界帮助的情况下理解这样的警告。仔细阅读该警告。 BTW malloc 可能会失败,你应该测试一下
  • 不是编程问题 OP需要一本C书
  • 如何测试mallocs 的结果 free-ing 使用后分配的结构...?

标签: c format-specifiers


【解决方案1】:

j 在这里使用时是 int* 类型:printf("%d",p1->j);printf 不喜欢这样,想要一个 int,所以你应该取消引用:

printf("%d",*(p1->j));

【讨论】:

    【解决方案2】:

    以下陈述

    p1->j=&p2->k; /* check the operator precedence */
    

    应该是

    p1->j=&(p2->k); /* j is type of ptr, it should hold address of k variable */
    

    同时访问 printf("%d",p1->j); -> printf("%d",*(p1->j)); 因为p1->j 产生的地址不是值。

    【讨论】:

    • 您能否详细说明 &p2->k 和 (&p2)->k ,我的理解是 &p2->k 给出了 k 值存储位置的实际地址 (&p2)->k给出 p2 的地址。还是我错了?
    • 由于->的优先级高于&,所以先解决p2->k,这不是本意。
    • 我的目的是获取k的地址
    • @bbcbbc1 那么应该是&(p2->k)
    • @achal 你搞错了,&p2->k 很好。
    猜你喜欢
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多