0

我一直在为此挠头好几个小时。这会将文本文件中的数据读取到结构中(每行有四个字符串,每行代表一个新学生)。我在 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;
}

是什么导致了这个段错误?

提前致谢,

格斯

4

2 回答 2

3

如果您的数组有studcount元素,则studentArray[studcount]超出数组的末尾,并且不允许写入。要访问的有效元素是0to studcount-1。您应该替换studentArray[studcount]studentArray[studcount-1]到处写入最后一个元素。

请注意,这样做会在循环完成时给你一个studcount太大的值1,因为数组的最后一个元素总是空的或不完整的。

正如 pmg 在评论中提到的,另一种解决方案是初始化studcount为 0,这将解决上述两个问题,但是您需要确保studcount+1在编写新元素之前至少为元素分配空间。

于 2011-07-13T14:06:07.603 回答
0

您的循环和 scanf 结构看起来错误..

首先你读取一个字符串(scanfwhile 条件中的),然后是一个 int(word== 1),然后是另一个字符串(又是 while 条件,word== 2),另一个字符串(又是 while 条件,word== 3),最后是另一个字符串和一个long long intword== 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 */;
}
于 2011-07-13T14:17:47.667 回答