【问题标题】:%d expecting int* in c [duplicate]%d 在 c 中期望 int* [重复]
【发布时间】:2016-08-21 15:05:28
【问题描述】:

据我所知, %d 需要一个 int 值。我不明白为什么 gcc 编译器说它需要 int* 。

这是我的代码:

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

struct student
{
    int rn, m[5];
    char nm[25];
};

int main()
{
    struct student* s[5];
    struct student **q=s;

    int i = 0;

    printf("Enter data");

    for(i=0;i<5;i++)
    {
        printf("\nStudent %d:\n",i+1);
        printf("Roll number: ");
        scanf("%d",(s[i])->rn);
        printf("\n%d",s[i]->rn);
    }
}

这是警告:

warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%d",(s[i])->rn);

【问题讨论】:

  • scanf 需要一个指针,因此它实际上可以更改 int 的值。
  • 另外s[i] 未初始化。

标签: c


【解决方案1】:

scanf 将一个值读入一个 int,它需要一个指向要读入的变量的指针。

scanf("%d",&((s[i])->rn));

【讨论】:

    【解决方案2】:

    printf%d 采用int,但scanf 采用intint *)的地址,因此它可以存储转换后的值。

    【讨论】:

      【解决方案3】:

      RTFM 在这里会有所帮助。 scanf 和相关函数(sscanf 等)总是需要它们将读取值的变量的指针。 scanf documentation

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-21
        • 2021-11-21
        • 2015-01-16
        • 1970-01-01
        • 2015-09-23
        • 2013-05-20
        • 2018-11-23
        • 2019-09-28
        相关资源
        最近更新 更多