我有一个应该从文件中读取,创建数据结构并返回的函数。函数工作,就在返回行之前,一切看起来都很好,结构看起来还不错。但是,该功能失败了 -
“运行时检查失败#2 - 变量'输出'周围的堆栈已损坏。”
该文件包含有关发电站和城市的信息。(输出,位置,名称等) 一些行是城市,有些是发电站,与行中的最后一个整数(或缺少行)不同。如果它是exsist(让我称之为X),这条线是一个发电站,接下来的X线就是连接它的城市。
这个功能。应该创建指向站点指针(站点**)的指针,所有城市都连接到每个站点。
station** read_from_file(FILE *file , station **power_grid){
int output , cities_connected ,i, counter = 0 ,j =0;
double x , y;
char name[256] = {0};
station *st;
while (fscanf(file, "%*c%[^\"]%*c%lf%lf%lf%d\n", name, &output, &x, &y, &cities_connected) != EOF){
counter++;
for( i = 0; i < cities_connected; i++){
fscanf(file , "%*c%[^\"]%*c%lf%lf%lf\n" , name , &output , &x ,&y);
}
}
power_grid = (station **)malloc(sizeof(station *)* counter);
rewind(file);
while (fscanf(file, "%*c%[^\"]%*c%lf%lf%lf%d\n", name, &output, &x, &y, &cities_connected) != EOF)
{
st = (station *)malloc(sizeof(station));
st->capacity = output;
st->cities_list = NULL;
st->num_of_cities = cities_connected;
st->name = (char *)malloc(strlen(name));
strcpy(st->name , name);
st->location[0] = x;
st->location[1] = y;
st->cities_list = (city **)malloc(sizeof(city *)*cities_connected);
for( i = 0; i < cities_connected; i++){
fscanf(file , "%*c%[^\"]%*c%lf%lf%lf\n" , name , &output , &x ,&y);
st->cities_list[i] = (city *)malloc(sizeof(city));
st->cities_list[i]->consumption = output;
st->cities_list[i]->location[0] = x;
st->cities_list[i]->location[1] = y;
st->cities_list[i]->name = (char *)malloc(strlen(name)+1);
strcpy(st->cities_list[i]->name , name);
}
power_grid[j] = st;
j++;
}
fclose(file);
return;
}
车站和城市结构 -
typedef struct city {
char * name;
double location[2];
double consumption;
}city;
typedef struct station {
char * name;
double location[2];
city ** cities_list;
int num_of_cities;
double capacity;
}station;
经过测试的文件 - here
答案 0 :(得分:0)
您的类型与此处不匹配:
fscanf(file, "%*c%[^\"]%*c%lf%lf%lf%d\n", name, &output, ...
,因为output
被声明为int
,而您使用的是%lf
。将其更改为%d
。
此外,当您为sr->name
分配内存时,您没有为name
本身和null终止符分配足够的空间。
结果,改变这个:
st->name = (char *)malloc(strlen(name));
到此:
st->name = malloc(strlen(name) + 1);
请注意,我没有投放malloc()
返回的内容,您也不应该(Do I cast the result of malloc?)。