我有關於從文件讀取數據到結構的問題 當我試圖運行此代碼時,我得到未處理的異常訪問衝突讀取位置0xcccccce0,錯誤發生在getData函數內部,爲什麼我得到這個錯誤,我該如何修復代碼?分配內存並從文件讀取輸入到結構數組
這是我的輸入文件
4
A,10
B,12
C,60
D,120
tutorY
我在的getData函數的意圖是先讀第一行拿到那麼4號,然後用這個數字來分配學生結構,然後閱讀接下來的四將文件行放入學生結構字段中,然後將最後一行讀入TUTOR結構中的tutorname feild。
預先感謝
#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;
}
中的getData功能很多的誤區。例如,在獲取第二個參數時(獲取(緩衝區,第一個+1,fp)!= NULL)的這些語句{if(count <= first)是最大緩衝區大小。沒有修改計數你正在比較它。結構指針的用法也都錯了 – 999k 2013-04-24 06:43:24
'... getData(STUDENT * studentArr [RECORDS_SIZE],...)'然後'* studentArr = malloc(...)'?你確定?那麼'getData(STUDENT ** studentArr,..)'呢呢? (你可以用'getData(&students,...)'來調用它,學生將成爲'學生*學生')。 – ShinTakezou 2013-04-24 06:53:33
我編輯的代碼計數現在遞增 – bluebk 2013-04-24 06:54:08