所以我有文件country.c:
struct City{
char* name;
char* food;
int population;
};
struct Country{
char *name;
int numCities;
pCity cities;
pTerritory countryTerr;
};
struct Territory{
int x1;
int x2;
int y1;
int y2;
};
typedef struct City* pCity;
typedef struct Country* pCountry;
typedef struct Territory* pTerritory;
void deleteCountry(pCountry country){
if(country != NULL){
int num_of_cities = country->numCities;
for(int i = 0 ; i<num_of_cities; i++){
if (country->cities){
free(country->cities[i].food);
free(country->cities[i].name);
free(country->cities[i]);
}
}
}
free(country->cities);
free(country->name);
free(country->countryTerr);
free(country);
}
}
pCity citySetter(pCity new_city, char* name, char* food,int popolution){
new_city = (pCity)malloc(sizeof(*new_city));
new_city->name = (char*)malloc((strlen(name)+1)*sizeof(char));
new_city->food = (char*)malloc((strlen(food)+1)*sizeof(char));
if (new_city->name)
strcpy(new_city->name,name);
if(new_city->food)
strcpy(new_city->food,food);
new_city->population = popolution;
return new_city;
}
status addCity(pCountry country,pCity city){
if (country==NULL || city==NULL)
return failure;
if(country->numCities==0)
country->cities = (pCity)malloc(sizeof(struct City));
else
country->cities =(pCity)realloc(country->cities,(country->numCities+1)*sizeof(struct City));
if(!country->cities)
return failure;
country->cities[country->numCities] = *city;
country->numCities++;
return success;
}
现在为了将城市添加到国家/地区,我首先使用“ citySetter”,然后使用
“ addCity”,在程序结尾,我称为“ deleteCountry”。
我正在使用valgrind来检测内存泄漏,并且它通知我我没有
释放我在“ citySetter”中创建的城市,因此我想删除每个城市
在城市数组中使用struct:
free(country->cities[i]);
但是我得到了编译错误,因为我指的是结构本身而不是
指针,如何访问数组中每个城市结构的地址
要释放它?