这是我的代码: int main() { typedef struct { int recordCount; char *firstName; char *secondName; char *id; char *email; }student; student *students = malloc(sizeof(*students)); int i = 0; while (students[i].firstName[0] != '.'){ stud
int main() {
typedef struct {
int recordCount;
char *firstName;
char *secondName;
char *id;
char *email;
}student;
student *students = malloc(sizeof(*students));
int i = 0;
while (students[i].firstName[0] != '.'){
students[i].firstName = (char *)malloc(sizeof(char*));
scanf("%s", students[i].firstName);
i++;
students = realloc(students, sizeof(students) * (i + 1));
}
}
当我通过for循环运行它时,它很有效,我很确定这只是我的while循环中的一些愚蠢行为.
malloc返回一块未初始化的内存.因此,student [i] .firstName是一个未初始化的指针,您尝试取消引用它.读取和取消引用未初始化的指针会调用未定义的行为,在这种情况下会表现为崩溃.当你为firstName成员分配空间时,你只为它指定sizeof(char *)字节,这是指针的大小,不一定是你想要读取的字符串的长度.
创建一个缓冲区来读取字符串,使其足够大,以满足您的需要,然后使用strdup创建一个副本以分配给相关指针.
student *students = NULL;
int i = 0;
char str[100];
scanf("%99s", str);
while (str[0] != '.'){
students = realloc(students, sizeof(*students) * (i+1));
students[i].firstName = strdup(str);
i++;
scanf("%99s", str);
}
