在分隔符处拆分字符串并将子字符串存储在C中的char **数组中

我想编写一个函数,通过第一次出现的逗号将用户在命令行上给出的字符串拆分并放入数组中。

这是我尝试过的:

char**split_comma(const str *s) { char *s_copy = s; char *comma = strchr(s_copy, ","); char **array[2]; *(array[0]) = strtok(s_copy, comma); *(array[1]) = strtok(NULL,comma); return array; } 

这是主要function:

 int main(int argc, char **argv) { char **r = split_comma(argv[1]); printf("substring 1: %s, substring 2: %s\n", r[0],r[1]); return 0; } 

有人可以给我一些见解,为什么这不起作用?

您需要为firstsecond目标字符串缓冲区分配足够的空间。

这是一个简单的解决方案,我们首先复制输入字符串s ,然后找到逗号并用字符串终止符(0)替换它。 然后第一个字符串位于s的开头,第二个字符串位于0之后:

 /* Caller must call free() on first */ void split_comma( char* s, char** first, char** second ) { char* comma; if(!s||!first||!second) return ; *first = strdup(s) ; comma=strchr(*first,',') ; if(comma) { *comma = 0 ; *second = comma + 1 ; } else *second = 0 ; } 

这很有效。

 char **split_on_comma(const char *s) { char ** result; result = malloc(sizeof(char*)*2); result[0] = malloc(sizeof(char) *200); result[1] = malloc(sizeof(char) *200); char *position; position = strchr(s, ','); strcpy(result[1], position +1); strncpy(result[0], s, position -s); return result; }