C警告“格式'%d'期望类型为'int *'的参数,但参数2的类型为'int'

时间:2018-10-30 19:03:19

标签: c warnings

我想用一个字符串和一些数字填充这些数组,但是似乎无法弄清楚为什么不能。

#include <stdio.h>

struct students{
char name[30];
int points[10];
int absences[10];
};

int main()
{
int i, n;
printf("Declare the number of students: ");
scanf("%d", &n);

struct students stud[n];

for (i = 0; i < n; i++) {
    printf("Name: ");
    scanf("%s", &stud[i].name);
    printf("Points: ");
    scanf("%d", &stud[i].points);
    printf("Absences: ");
    scanf("%d", &stud[i].absences);
}


for( i = 0; i < n; i++)
{
    printf("%s\n", stud[i].name);
    printf("%d\n", stud[i].points);
    printf("%d\n", stud[i].absences);

}


}

这是我得到的警告:

警告:格式'%s'期望为'char '类型的参数,但是参数2为'char()[30]'类型[-Wformat =]

     scanf("%s", &stud[i].name);

feladat1.c:21:15:警告:格式'%d'期望类型为'int '的参数,但是参数2的类型为'int()[10]'[-Wformat = ]

     scanf("%d", &stud[i].points);

feladat1.c:23:15:警告:格式'%d'期望类型为'int '的参数,但是参数2的类型为'int()[10]'[-Wformat = ]

     scanf("%d", &stud[i].absences);

feladat1.c:30:16:警告:格式'%d'期望类型为'int'的参数,但是参数2的类型为'int *'[-Wformat =]

     printf("%d\n", stud[i].points);

feladat1.c:31:16:警告:格式'%d'期望类型为'int'的参数,但是参数2的类型为'int *'[-Wformat =]

     printf("%d\n", stud[i].absences);

2 个答案:

答案 0 :(得分:1)

  1. struct students中,int points[10];应该是int points;int absences[10];应该是int absences;

  2. scanf("%s", &stud[i].name);行应为scanf("%s", stud[i].name);

关注code可能会起作用:

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

struct students{
    char name[30];
    int points;
    int absences;
};

int main()
{
    int i, n;
    printf("Declare the number of students: ");
    scanf("%d", &n);

    struct students *stud = malloc(sizeof(struct students) * n);

    for (i = 0; i < n; i++) {
        printf("Name: ");
        scanf("%s", stud[i].name);
        printf("Points: ");
        scanf("%d", &stud[i].points);
        printf("Absences: ");
        scanf("%d", &stud[i].absences);
    }


    for( i = 0; i < n; i++)
    {
        printf("%s\n", stud[i].name);
        printf("%d\n", stud[i].points);
        printf("%d\n", stud[i].absences);

    }
    return 0;
}

答案 1 :(得分:0)

尝试此代码

#include <stdio.h>
struct students{
    char name[30];
    int points;
    int absences;
};

int main()
{
    int i, n;
    printf("Declare the number of students: ");
    scanf("%d", &n);

    struct students stud[n];

    for (i = 0; i < n; i++) {
        printf("Name: ");
        scanf("%s", stud[i].name);
        printf("Points: ");
        scanf("%d", &stud[i].points);
        printf("Absences: ");
        scanf("%d", &stud[i].absences);
    }


    for( i = 0; i < n; i++)
    {
        printf("%s\n", stud[i].name);
        printf("%d\n", stud[i].points);
        printf("%d\n", stud[i].absences);

    }
    return 0;
}