试一试:
#include <stdlib.h>
#include <string.h>
...
void split(char *str, char **splitstr)
{
char *p;
int i=0;
p = strtok(str,",");
while(p!= NULL)
{
printf("%s", p);
splitsr[i] = malloc(strlen(p) + 1);
if (splitstr[i])
strcpy(splitstr[i], p);
i++;
p = strtok (NULL, ",");
}
}
然后,在main
:
#define MAX_LEN ... // max allowed length of input string, including 0 terminator
#define MAX_STR ... // max allowed number of substrings in input string
int main(void)
{
char input[MAX_LEN];
char *strs[MAX_STR] = {NULL};
...
split(input, strs);
...
}
一些解释。
strs
定义于main
作为一个指针数组char
。每个数组元素将指向从输入字符串中提取的字符串。在 main 中,分配的只是指针数组,每个元素最初都是 NULL;每个元素的内存将在split
函数使用malloc
,基于子字符串的长度。某处当你完成后strs
您将需要使用释放这些指针free
:
for (i = 0; i < MAX_STR; i++)
free(strs[i]);
现在,为什么是splitstr
声明为char **
代替char *[MAX_STR]
?除非它是操作数sizeof
or &
运算符,或者是用于在声明中初始化另一个数组的字符串文字,数组表达式的类型将隐式转换为N-element array of T
to pointer to T
,表达式的值将是数组中第一个元素的位置。
当我们打电话时split
:
split(input, strs);
数组表达式input
从类型隐式转换char [MAX_LENGTH]
to char *
(T == char
) 和数组表达式strs
从类型隐式转换char *[MAX_STRS]
to char **
(T == char *
). So splitstr
接收两个参数的指针值,而不是数组值。