[英]C programming language, adjacency matrix
在您的幫助下,我可以從文本文件(input.txt)中獲取輸入,其中行由city1 city2 distance ...組成,並在矩陣中重復輸入城市名稱。 根據這個矩陣,我編寫了一段代碼,將它們的距離添加到鄰接矩陣中。 但是我的意思是輸出看起來很奇怪,這是不正確的。 我猜下面的代碼中應該缺少或錯誤的東西。 非常感謝任何幫助。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[]){
int i=1,j, state=0, k, dist,x=0,y=0;
int** myMat;
char *city1, *city2, **matnames;
FILE* p;
city1 = (char*) malloc(sizeof(char));
city2 = (char*) malloc(sizeof(char));
matnames = (char**) malloc(sizeof(char*));
myMat = (int**) malloc(sizeof(int*)*4);
p = fopen(argv[1],"r");
/************************************************************/
matnames[0] = (char*) malloc(sizeof(char));
matnames[1] = (char*) malloc(sizeof(char));
matnames[2] = (char*) malloc(sizeof(char));
matnames[2] = NULL;
fscanf(p, "%s %s %d", city1, city2, &dist);
strcpy(matnames[0],city1);
strcpy(matnames[1],city2);
/************************************************************/
for(i=0;i<3;i++){
myMat[i] = (int*) malloc(sizeof(int));
}
myMat[1][2] = dist; /* the first two distances placed at matnames */
myMat[2][1] = dist;
/************************************************************/
while( fscanf(p,"%s %s %d",city1,city2, &dist) != EOF){
for(j=0; matnames[j]!=NULL; j++){
if( strcmp(matnames[j], city1) != 0){
state++;
}
}
if(state == j){
matnames = realloc(matnames, sizeof(char*)*(j+3));
matnames[j] = (char*) malloc(sizeof(char));
strcpy(matnames[j], city1);
matnames[j+1] = (char*) malloc(sizeof(char));
matnames[j+1] = NULL;
}
state = 0;
for(j=0; strcmp(matnames[j], city1) != 0;j++){
x++; /* "x" finds the city1 indeks from matnames*/
}
for(k=0; matnames[k] != NULL;k++){
if( strcmp(matnames[k], city2) != 0){
state++;
}
}
if(state == k){
matnames = realloc(matnames, sizeof(char*)*(k+4));
matnames[k] = (char*) malloc(sizeof(char));
matnames[k+1] = (char*) malloc(sizeof(char));
strcpy(matnames[k], city2);
matnames[k+1] = NULL;
}
state = 0;
/* till to here the names of cities are placed in matnames without repetion*/
for(j=0; strcmp(matnames[j], city2) != 0;j++){
y++; /* "y" finds the city2 indeks from matnames*/
}
/****** the problem should be in this part */
myMat = realloc(myMat,sizeof(int*)*(k+3));
for(i=2;i<k+2;i++){
myMat[i] = (int*) malloc(sizeof(int));
}
myMat[x][y] = dist;
myMat[y][x] = dist;
x=0; y=0;
}
return 0;
}
您將1個char分配給city1和city2(具有sizeof(char)的malloc)。 除非您的城市都只有一個字符,否則fscanf將超出范圍。
使用city1 =(char *)malloc(1024)再試一次,因此城市可能更長一些。
matnames並不是很明顯,但您為其分配了1個sizeof(pointer),即4個字節。 然后,執行matnames [0] = ...,matnames [1] = ... matnames [1]已經溢出分配的內存。 所以你在隨機的地方寫作。
C語言在內存分配方面非常寬容,但結果完全不可預測。 確保您的malloc有足夠的空間,並在可能的情況下考慮使用其他語言。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.