我正在尝试读取由多行组成的文件文本(input.txt),例如 AB 120 CB 60 ...
好吧,现在我正在尝试将可能在该文件中重复多次的名称传输到一个双指针,它们应该只显示一次。在下面的代码中,我得到了其中的一些,但我也遇到了分段错误。我不知道我错过了什么或出了什么问题。你的任何一点帮助都会对我有很大帮助。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
int i=1, state=0, k, dist;
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*));
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);
/************************************************************/
while( fscanf(p,"%s %s %d",city1,city2, &dist) != EOF){
for(k=0; matnames[k]!=NULL; k++){
if( strcmp(matnames[k], city1) != 0){
state++;
}
}
if(state == k){
matnames[k] = (char*) malloc(sizeof(char));
strcpy(matnames[k], city1);
matnames[k+1] = (char*) malloc(sizeof(char));
matnames[k+1] = NULL;
}
state = 0;
for(k=0; matnames[k] != NULL;k++){
if( strcmp(matnames[k], city2) != 0){
state++;
}
}
if(state == k){
matnames[k] = (char*) malloc(sizeof(char));
matnames[k+1] = (char*) malloc(sizeof(char));
strcpy(matnames[k], city2);
matnames[k+1] = NULL;
}
state = 0;
}
return 0;
}