我对从文件读取数据到结构有疑问 当我尝试运行此代码时,出现未处理的异常访问冲突读取位置 0xcccccce0,错误发生在 getData 函数内,为什么我会收到此错误,我应该如何修复代码?
这是我的输入文件
4
A,10
B,12
C,60
D,120
tutorY
我在 getData 函数中的意图是首先读取第一行以获取数字 4,然后使用该数字为学生结构分配,然后将文件的接下来四行读入学生结构字段,然后读取最后一行进入 TUTOR 结构中的 coachname field。
提前致谢
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "queue.h"
#include "stack.h"
#define RECORDS_SIZE 100
#define NAME_SIZE 20
typedef struct Student
{
char nameStudent[NAME_SIZE];
int TimeIn;
int TimeUpdate;
}STUDENT;
typedef struct TUTOR
{
char nameTutor[NAME_SIZE];
int TutorTIme;
STUDENT *ptr;
}TUTOR;
QUEUE *queue1;
STACK *stack1;
void getData(STUDENT *studentArr[RECORDS_SIZE], TUTOR tutorArr[1]);
int main (void)
{
STUDENT *studentArr[RECORDS_SIZE];
TUTOR tutorArr[1];
FILE *fp = NULL;
getData(studentArr, tutorArr);
return 0;
}
void getData(STUDENT *studentArr[RECORDS_SIZE], TUTOR tutorArr[1])
{
FILE *fp;
char fileName[NAME_SIZE];
char buffer[RECORDS_SIZE];
int first = 0;
int count = 1;
printf("Enter file name: ");
gets(fileName);
fp = fopen(fileName, "r");
if (fp == NULL)
{
printf("Error! The file does not exist!\n");
}
fscanf(fp,"%d",&first);
*studentArr = (STUDENT*) malloc(first*sizeof(STUDENT));
while( fgets(buffer, first +1, fp) != NULL)
{
if (count <= first)
{
sscanf(buffer, "%[,]%d", studentArr[count]->nameStudent, studentArr[count]->TimeIn);
printf("%s,%d", studentArr[count]->nameStudent, studentArr[count]->TimeIn);
}
else
sscanf(buffer, "%s", tutorArr[count].nameTutor);
count++;
}
return;
}
最佳答案
我发现了一些问题。
第一个 fscanf 首先读取将读取第一个数字,然后留下该行的其余部分(“\n”)由第一次调用 fgets 获取
更重要的是,studentArr 是一个指针数组,大概每个学生都有一个元素,但 malloc 只分配 sudentArr 中的第一个指针,所有其他指针都包含垃圾,这导致了访问冲突。
关于c - 分配内存并将输入从文件读取到结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16184771/