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」...)'來防止緩衝區溢出 –