问题
I've been stuck on this project for the better part of the week and while I have been grinding through syntax errors.
The gist of the project is to read through the headers and stopping at a certain column and finding certain characteristics like the min, max and average of the column. However, I am having a tough time with memory allocation for this job. I have been unable to further my code so far because I keep getting an error labeled Segmentation Fault: 11
.
The bolded section is what I have narrowed the problem down to. I know there is a memory problem but I cannot see why fgets is not reading in the first line of the file from within the function. The file does not return NULL either and is able to be accessed. Dynamic arrays are an option but I am a beginner and very unfamiliar with them.
double getMin(char csvfile[], char column[])
{
int counter= 0;
int counter2= 0;
char* token;
char type;
char activity[20];
int chap, sec;
int min = -1000;
char header[20];
char *res;
char row[3000];
char Toprow[3000];
sscanf(column, "%c%d.%d", &type, &chap, &sec);
if (type!='P' && type!='C' && type!='L') return -2.0;
if (chap<=0 || sec<=0) return 0;
if(type == 'c' || type == 'C'){
sprintf(activity,"%challange", type);
}
else if(type == 'P' || type == 'p'){
sprintf(activity,"%carticipation", type);
}
else {
sprintf(activity,"%cab", type);
}
sprintf(header, "%d.%d - %s", chap, sec, activity);
FILE* inFile = NULL;
inFile = fopen("array.csv","r");
//This is where the trouble begins that Ive narrowed down to
while(!feof(inFile)){
fgets(Toprow, 3000, inFile);
while(token != NULL){
counter = counter + 1;
token = strsep(&Toprow, ",");
printf("%s", token);
res = strstr(token, header);
if(res){
break;
token = NULL;
}
}
}
while (!feof(inFile)) {
int currVal= 0;
fgets(row, 3000, inFile);
if(feof(inFile)) break;
while( (token = strsep(&row, ',')) != NULL){
++counter2;
if(counter2 == counter){
res = strstr(token, header);
if(!res){
int currVal = atoi(*token);
if(currVal > min)
min = currVal;
counter2 = 0;
break;
}
}
}
}
return min;
}
The excel file looks like this for reference enter image description here
来源:https://stackoverflow.com/questions/58458345/segmentation-fault-while-trying-to-parse-an-excel-style-csv-file-c-programming