-1
我在我的代碼中遇到了一些問題,我無法修復它。任何人都可以抓住mycode的缺陷嗎?我想從輸入文件中獲取城市距離,並在地圖上覆制城市名稱而不重複。我的問題是分段錯誤。輸入文件由幾行兩個城市名稱和它們之間的距離組成,我嘗試獲取城市名稱並將它們複製到名爲map的雙指針。對不起,對不起英語
city1[0] = (char*)malloc(sizeof(char)*10);
city2[0] = (char*)malloc(sizeof(char)*10);
map[0] = (char*)malloc(sizeof(char)*10);
map[1] = (char*) malloc(sizeof(char)*10);
map[2] = (char*) malloc(sizeof(char));
map[2] = NULL;
fscanf(data, "%s %s %d", city1[0], city2[0], &distance);
strcpy(map[0],city1[0]);
strcpy(map[1],city2[0]);
j=2,i=1;
while(fscanf(data, "%s %s %d",city1[i],city2[i], &distance)!=EOF){
city1[i+1] = (char*)malloc(sizeof(char) *10);
city2[i+1] = (char*)malloc(sizeof(char)*10);
if(checker(map,city1[i])==1){
map = realloc(map, sizeof(char*)*(j));
map[j] = (char*) malloc(sizeof(char));
strcpy(map[j], city1[i]);
map[j+1] = (char*) malloc(sizeof(char));
map[j+1] != NULL;
j++;
}
if(checker(map,city2[i])==1){
map = realloc(map, sizeof(char*)*(j));
map[j] = (char*) malloc(sizeof(char));
map[j+1] = (char*) malloc(sizeof(char));
strcpy(map[j], city2[i]);
map[j+1] = NULL; j++;
}
}
不要強制'malloc'的返回值:http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – wap26
「我在我的代碼中遇到了一些問題」你會告訴我們問題是什麼,或者讓我們猜測? – cdarke
當你去看醫生時,你只是說「哎呀!」? – Jens