[英]String arrays in C segmentation fault
我正在尝试创建一个字符串数组并将字符串传递给该数组。
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;
}
结果我得到了
segmentation fault(core dumped)
当我尝试做这样的事情
char *test = NULL;
strcpy(test, "hello");
return 0;
我再次遇到相同的细分错误。 虽然当分配这样的空间时:
char *test = (char *) malloc(100);
没有问题。 但是当我这样做时:
char test[100];
也没有问题。 所以这就是为什么我什至不理解分割错误的原因
char strings[100][100];
代替
char *strings[100];
以下分配一个指针,并将该指针设置为指向100个字符的单个数组。 IE浏览器没有地方插入100个城市字符串。
char *test = NULL;
strcpy(test, "hello");
return 0;
....
char *test = (char *) malloc(100);
....
以下声明了一个100字节的数组,没有空间容纳100个城市字符串
char test[100];
以下语句声明了一个包含100个字符数组的数组,其中每个数组长100个字节
char strings[100][100];
以下声明了一个数组,其中包含100个指向char的指针,而不是100个字符串。 因此,您需要为每个城市字符串“分配”空间,并将该指针插入数组中适当的偏移量中。
char *strings[100];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.