我一直在摸不着头脑。这将数据从文本文件读取到结构中(每行有四个字符串,每行代表一个新学生)。我在realloc(接近结尾)上遇到了一个seg错误。我怀疑我不理解指针如何与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;
}
造成这种段错的原因是什么?
提前致谢,
格斯
答案 0 :(得分:3)
如果您的数组有studcount
个元素,那么studentArray[studcount]
超过了数组的末尾,并且不允许写入数组。要访问的有效元素是0
到studcount-1
。您应该将studentArray[studcount]
替换为studentArray[studcount-1]
,以便写入最后一个元素。
请注意,这样做会在循环完成时为studcount
提供一个1
的值太大,因为数组的最后一个元素总是空的或不完整的。
正如评论中的pmg所提到的,另一种解决方案是将studcount
初始化为0,这将解决上述问题,但是您需要确保为至少studcount+1
个元素分配空间在写一个新的之前。
答案 1 :(得分:0)
你的循环和scanf结构看起来不对..
首先你读取一个字符串(while条件中的scanf
),然后是int(word
== 1),然后是另一个字符串(再次调整条件,word
== 2),另一个字符串(同时再次调整word
== 3),最后是另一个字符串和long long int
(word
== 4)。
我用开关重写你的内循环
/* pseudo-code */
while (fgets(buf, sizeof buf, stdin)) {
/* realloc here */
chk = sscanf(buf, "%4d%20s%20s%10lld",
&studentArray[studcount].studentID,
studentArray[studcount].lastName,
studentArray[studcount].firstName,
&studentArray[studcount].phoneNumber);
if (chk != 4) /* deal with error */;
}