c - 在结构数组上使用 realloc

标签 c arrays struct realloc

我已经为此绞尽脑汁好几个小时了。这会将文本文件中的数据读取到结构中(每行有四个字符串,每行代表一个新学生)。我在 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] 就超过了数组的末尾,不允许在那里写入。要访问的有效元素是 0studcount-1。您应该将 studentArray[studcount] 替换为 studentArray[studcount-1] 以写入最后一个元素。

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

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

关于c - 在结构数组上使用 realloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6680138/

相关文章:

C 将指针传递给指向函数的指针并使用 malloc

c - 在 Sublime Text 3 中构建和运行 C 时的警告消息

c - 使用 Glade 时在 GTK-Notebook 中添加选项卡

javascript - 拼接然后修改数组

ios - 将简单数组连接到嵌套数组逻辑困惑

java - 将数组从最高到最低排序

c - 结构中的指针——未知大小的数组

c - --PIC32MX 启动闪存上的填充命令

ios - 从 Swift 中的数据模型返回更具体的对象

C - 结构到指针