I'm trying to create an array of strings and pass strings to this array.
struct node {
int vertex_no;
};
int main() {
char city1[100], city2[100], buffer[999];
int distance;
FILE *fp;
fp = fopen("cities.txt", "r+");
if(fp == NULL)
perror("Error");
//Change - characters with space
while(1) {
char ch = fgetc(fp);
if(ch == '-') {
fseek(fp, ftell(fp)-1, SEEK_SET);
fputc(' ', fp);
}
if(ch == EOF)
break;
}
//Get to beginning of the file
fseek(fp, 0, SEEK_SET);
//Pass first line
fgets(buffer, sizeof(buffer), fp);
int i, j, v = 0;
char cities[100][100];
for(i = 0; i < 100; i++)
for(j = 0; j < 100; j++)
cities[i][j] = '\n';
int vertices = 0;
int add = 1;
//Find how many vertices we have
while(fscanf(fp, "%s %s %d", city1, city2, &distance) == 3) {
if(cities[0][0] == '\n') {
strcpy(cities[0], city1);
strcpy(cities[1], city2);
v = 2;
}
for(i = 0; cities[i][0] != '\n'; i++) {
//Search city1 inside cities array
if( strcmp(cities[i], city1) == 0 ) {
add = 0;
break;
}
//If not found add it to array
if(add) {
strcpy(cities[v], city1);
v++;
}
//Same search for city2
add = 1;
if( strcmp(cities[i], city2) == 0 ) {
add = 0;
break;
}
//If not found add it to array
if(add) {
strcpy(cities[v], city2);
v++;
}
}
}
for(i=0;cities[i][0] != '\n';i++)
printf("City no.%d = %s\n", i, cities[i]);
printf("Last city1, city2 and distance: %s, %s, %d", city1, city2, distance);
return 0;
}
As a result I get
segmentation fault(core dumped)
When I try to do something like this
char *test = NULL;
strcpy(test, "hello");
return 0;
I get the same segmentation fault again. Although when allocate space like this:
char *test = (char *) malloc(100);
There is no problem. But when I do like this:
char test[100];
There is also no problem. So that's why I don't understand the reason of getting segmentation fault even tho I used
char strings[100][100];
instead of
char *strings[100];