gets(edu.classes [i] .students [j] .name);構造体 - なぜscanfと比較して関数が機能しないのですか?
コンパイラがデバッグ後にこの行をスキップし、名前に入力しない理由を知りたいのですが?その方法で関数を呼び出すのは合法ですか?
注: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'を使用します。 –
私は 'gets'の代わりに' fgets'を使うことをお勧めします。そのエラーが起こりやすい –
は、なぜこれがうまくいかないのか分かりません。バッファオーバーフローから保護するために 'scanf("%19s "...)'を使用してください。 –