gets(edu.classes [i] .students [j] .name);结构 - 为什么得到函数不能比较scanf?
我想知道为什么编译器跳过这一行后调试,并没有输入名称?这种方式调用gets函数是否合法?
注意:一旦我使用scanf(“%s”,...) - 它的工作原理!
scanf(“%s”,edu.classes [i] .students [j] .name);
(我知道我没有释放内存分配和检查,如果分配没有失败! - 我知道这是必要这只是时间问题):)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 20
typedef struct
{
char name[SIZE];
int id;
}Student;
typedef struct
{
Student *students;
int num_students;
char teacher[SIZE];
}Class;
typedef struct
{
Class *classes;
int num_classes;
}Education;
int main()
{
int i, j;
Education edu;
puts("how many classes?");
scanf("%d", &(edu.num_classes));
edu.classes = (Class*)malloc((edu.num_classes) * sizeof(Class));
if (edu.classes == NULL)
{
printf("ERROR allocation\n");
exit(1);
}
for (i = 0; i < edu.num_classes; i++)
{
puts("enter num of students");
scanf("%d", &(edu.classes[i].num_students));
edu.classes[i].students = (Student*)malloc((edu.classes[i].num_students)
* sizeof(Student));
for (j = 0; j < edu.classes[i].num_students; j++)
{
puts("enter student's name");
gets(edu.classes[i].students[j].name); // this is the problematic line
puts("enter id");
scanf("%d", &(edu.classes[i].students[j].id));
}
}
return 0;
}
_never_使用'gets'。 –
我会推荐使用'fgets'而不是'gets',它的容易出错的 –
表示,我不知道为什么这不起作用。使用'scanf(“%19s”...)'来防止缓冲区溢出 –