我正在与学生建立数据库,我已经创建了struct Students
struct Students {
//struct specific for students
char first_name[30];
char last_name[30];
int ssn;
};
void add_student() {
//function to add students
int i, n;
struct Students *student;
printf("How many students are you adding");
scanf("%d", &n);
student = (struct Students *)malloc(n * sizeof(struct Students *)); //allocate the memory for n students
for (i = 0; i < n; i++) {
printf("Enter first, last and ssn respectively");
scanf(" %s ", &(student+i)->first_name); //adds first name to student i
scanf(" %s ", &(student+i)->last_name);// adds last name to student i
scanf(" %d ", &(student+i)->ssn); //adds ssn to student i
}
for (i = 0; i < n; i++) {
//print each of the students being added
printf("First name: %s\n ", (student+i)->first_name);
printf("Last name: %s\n ", (student+i)->last_name);
printf("ssn: %d\n ", (student+i)->ssn);
}
free(student); //free the memory used
}
预期:我正在尝试为数据库添加学生并打印出来 以确保它们实际上已被写入结构。
实际:
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[30]’ [-Wformat=]
scanf(" %s ", &(student+i)->first_name);
答案 0 :(得分:2)
只需将数组作为参数传递,它将衰减为指向其第一个元素的指针:
scanf("%s", student[i].first_name);
您正在传递数组的地址,该数组的值与第一个元素的地址相同,但类型不同。编译器检测到此类型不匹配并发出警告(这是非常的一件好事!)
以下是代码中其他问题的列表:
scanf()
的返回值,以检测无效或缺少的输入。scanf()
输入的值添加有效性测试。Students
数组分配的内存不正确:您在指针大小的情况下分配n
,而在{{1}大小的情况下分配n
}本身。Student struct
格式字符串中的尾随空格。这些会导致无缘无故地读取多余的输入。scanf()
。"%29s"
的返回值以检测缺少的输入。这是更正的版本:
scanf()
答案 1 :(得分:1)
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2
has type ‘char (*)[30]’ [-Wformat=]
之所以显示此警告,是因为您在扫描&
和(student+i)->first_name
时使用了(student+i)->last_name
。扫描 string 时,无需在变量名前放置&
。请注意,&
必须在所有其他变量类型之前使用。
将其更改为行:
scanf(" %s ", &(student+i)->first_name);
scanf(" %s ", &(student+i)->last_name);
收件人
scanf(" %s ", (student+i)->first_name);
scanf(" %s ", (student+i)->last_name);
警告将消失