这个问题使我感到沮丧;我之前已经解决了,但我不记得究竟是怎么回事了,它一次又一次地出现了!
你给了一个字符串,就像一个水果列表,用逗号分隔。您希望将字符串拆分为逗号中的字符串数组。我无法弄清楚为什么我一直在分段错误!这是我的代码:
char** split(char *);
int count_words(char *);
int main(int argc, char **argv) {
char *my_list = "Apple, banana, cherry, dragonfruit, elderberry";
char **split_list = split(my_list);
/*int i = 0;
while(split_list[i] != NULL) {
printf("%s\n", split_list[i]);
i++;
}*/
return 0;
}
char** split(char *str) {
int num_words = count_words(str);
char **my_words = malloc((num_words + 1) * sizeof(char*));
const char delim[2] = ",";
char *token;
token = strtok(str, delim);
for(int i = 0; i < num_words; i++) {
my_words[i] = malloc(sizeof(char) * strlen(token));
strcpy(my_words[i], token);
token = strtok(NULL, delim);
}
my_words[i] = NULL;
return my_words;
}
int count_words(char *str) {
int cnt = 0;
while(*str != '\0') {
if(*str == ',') cnt++;
str++;
}
return ++cnt;
}
答案 0 :(得分:2)
我的天哪,我有一个巨大的脑力......
答案很简单,我使用的字符串是一个具有只读访问权限的常量。
声明一个这样的字符串:char *myStr = "Hello World"
是只读的!你不能写入它。
解决方案代码:
char** split(char *);
int count_words(char *);
int main(int argc, char **argv) {
const char *string = "Apple, banana, cherry, dragonfruit, elderberry";
char *my_list = malloc(1 + strlen(string)); //random number
strcpy(my_list, string);
char **split_list = split(my_list);
int i = 0;
while(split_list[i] != NULL) {
printf("%s\n", split_list[i]);
free(split_list[i]);
i++;
}
free(split_list);
free(my_list);
return 0;
}
char** split(char *str) {
int num_words = count_words(str);
char **my_words = malloc((1 + num_words) * sizeof(char*));
const char delim[2] = ",";
char *token;
token = strtok(str, delim);
int i = 0;
while(token != NULL) {
my_words[i] = malloc(sizeof(char) * (1 + strlen(token)));
strcpy(my_words[i], token);
token = strtok(NULL, delim);
i++;
}
my_words[i] = NULL;
return my_words;
}
int count_words(char *str) {
int cnt = 0;
while(*str != '\0')
{
if(*str == ',')
cnt++;
str++;
}
return ++cnt;
}