【发布时间】:2021-07-21 07:17:16
【问题描述】:
代码如下:
#include <stdio.h>
int main()
{
struct date
{
int year;
int month;
int day;
};
struct address
{
char city[15];
char district[15];
};
struct student
{
char name[25];
int roll_no;
struct date DOB;
struct address add;
};
struct student BIM[10];
int i;
for(i=0;i<11;i++)
{
printf("Enter student name: ");
scanf("%s",BIM[i].name);
printf("Enter roll no: ");
scanf("%d",&BIM[i].roll_no);
printf("Enter Date of birth: ");
scanf("%d %d %d",BIM[i].DOB.year,BIM[i].DOB.month,BIM[i].DOB.day);
printf("Enter address: ");
scanf("%s %s",BIM[i].add.district,BIM[i].add.city);
}
int roll;
printf("Enter roll no: ");
scanf("%d",&roll);
for(i=0;i<11;i++)
{
if(roll==BIM[i].roll_no)
{
printf("Name : %s",BIM[i].name);
printf("Roll no : %d",BIM[i].roll_no);
printf("DOB : %d/%d/%d",BIM[i].DOB.year,BIM[i].DOB.month,BIM[i].DOB.day);
printf("Address : %s,%s",BIM[i].add.district,BIM[i].add.city);
break;
}
}
}
程序在第一次循环中取 DOB 后结束。
以下是警告:
main.c:32:17: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%d %d %d",BIM[i].DOB.year,BIM[i].DOB.month,BIM[i].DOB.day);
main.c:32:20: warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘int’ [-Wformat=]
scanf("%d %d %d",BIM[i].DOB.year,BIM[i].DOB.month,BIM[i].DOB.day);
main.c:32:23: warning: format ‘%d’ expects argument of type ‘int *’, but argument 4 has type ‘int’ [-Wformat=]
scanf("%d %d %d",BIM[i].DOB.year,BIM[i].DOB.month,BIM[i].DOB.day);
【问题讨论】:
-
您是在问如何修复警告或为什么程序不等待更多输入?
-
警告告诉您,您向
scanf提供了错误的参数。如果在预期地址时传递整数,则会导致未定义的行为,这可能会导致崩溃。此外,您应该始终检查任何 I/O 函数的返回值,例如scanf。 -
您有一个 10 个元素的数组,并且想要在该数组中使用 11 个元素?这没有任何意义。
-
至于程序退出的原因,不使用
printf的正确参数类型会调用未定义的行为,在这种情况下会导致程序崩溃。
标签: c