我的 C 程序崩溃了,我太新了,无法弄清楚。到目前为止它非常简单,我想代码足以找出问题所在。
我只是想逐行读取文件。一旦内存不足,我会将结构的内存加倍。如果这还不够信息,我会提供您需要的任何其他信息。
非常感谢您的帮助,因为我已经被困了好几个小时了。
/*
John Maynard
1000916794
7/15/2013
HW-06
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
struct course
{
char subject[11];
int catalogNum;
int sectionNum;
int enrollmentTotal;
int enrollmentCap;
};
void readFile(struct course *d, char* filename);
void double_array_size(struct course *d, int new_size);
int main(void)
{
char *filename = "hw06-data.csv";
struct course *d;
d = malloc( N * sizeof(struct course));
readFile(d, filename);
}
void readFile(struct course *d, char* filename)
{
FILE* fp;
char buffer[100];
int i = 0, array_size = 100;
struct course *temp;
if( ( fp = fopen(filename, "r") ) == NULL)
{
printf("Unabale to open %s.\n", filename);
exit(1);
}
fgets(buffer, sizeof(buffer), fp);
while( fgets(buffer, sizeof(buffer), fp) != NULL)
{
if (i == array_size)
{
array_size *= 2;
double_array_size(d, array_size);
printf("reached limit...increasing array to %d structures\n", array_size);
}
i++;
}
fclose( fp );
}
void double_array_size(struct course *d, int new_size)
{
struct course *temp;
temp = realloc(d, new_size * sizeof(struct course));
if(temp == NULL)
{
printf("unable to reallocate\n");
exit(1);
}
else
d = temp;
}