I'm trying to read a file text(input.txt) which consists of multiple line like A B 120 C B 60...
Well, now I'm trying to transfer the names that may have been repeated more than once in that file into a double pointer where they should be shown only once. In my code below I get some of them but I also get a segmentation fault. I don't know what I am missing or what's wrong. Any little help of yours could help me very much.
#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;
}
malloc(sizeof(char))allocates memory for a single char so yourfscanfcalls overflowcity1andcity2.free()orfclose(). You should practice better resource management to avoid leaking memory or file handles.