我已经为此绞尽脑汁好几个小时了。这会将文本文件中的数据读取到结构中(每行有四个字符串,每行代表一个新学生)。我在 realloc 上遇到段错误(接近尾声)。我怀疑我不了解指针如何与 malloc/realloc 交互。
struct student* createInitialStudentArray(FILE *fp) {
char buf[20+1] = {0};
int word = 1, studcount = 1;
struct student* studentArray = malloc(sizeof(struct student));
assert(studentArray != NULL);
while (fscanf(fp, " %20s", buf) != EOF) {
if (word % 4 == 1) {
sscanf(buf, "%4d", &studentArray[studcount].studentID);
word++;
}
else if (word % 4 == 2) {
strcpy(studentArray[studcount].lastName, buf);
word++;
}
else if (word % 4 == 3) {
strcpy(studentArray[studcount].firstName, buf);
word++;
}
else if (word % 4 == 0) {
sscanf(buf, "%10lld", &studentArray[studcount].phoneNumber);
word = 1;
studcount++;
studentArray = realloc(studentArray, studcount * sizeof(struct student));
assert(studentArray != NULL);
}
}
return studentArray;
}
是什么导致了这个段错误?
提前致谢
古斯
最佳答案
如果你的数组有 studcount
元素,那么 studentArray[studcount]
就超过了数组的末尾,不允许在那里写入。要访问的有效元素是 0
到 studcount-1
。您应该将 studentArray[studcount]
替换为 studentArray[studcount-1]
以写入最后一个元素。
请注意,当循环完成时,这样做会得到一个 studcount
值,这个值太大了 1
,因为数组的最后一个元素总是空的或不完整的。
正如 pmg 在评论中提到的,另一种解决方案是将 studcount
初始化为 0,这将解决上述两个问题,但是您需要确保至少为 分配空间studcount+1
个元素,然后再编写一个新元素。
关于c - 在结构数组上使用 realloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6680138/