c-将strtok结果插入char*(增加了动态)



我疯了。我想用空格分割字符串(char*text),并将字符串结果插入到数组中,然后返回这个数组。我在C 中有以下方法

char *read_command(char *text)
{
int index=0;
char *res=NULL;
char *command= (char*)malloc(strlen(text)+1);
strcpy(command, text);
char *tok = strtok(command, " ");
while(tok!=NULL && index ==0)
{
res = (char*)realloc(res, sizeof(char)*(index+1));
char *dup = (char*)malloc(strlen(tok)+1);
strcpy(dup, tok);
res[index++] = dup; //Error here
tok = strtok(NULL, " ");
}
res[index++]='';
return res;
}

来自主方法

char *input="read A B C";
char *command = read_command(input);

谢谢

您在这个调用中使用了错误的类型来计算大小:

res = realloc(res, sizeof(char)*(index+1));

您需要使用char*,而不是charsizeof,如下所示:

res = realloc(res, sizeof(char*)*(index+1));

由于您的代码返回一个指向C字符串的指针(表示为char*),因此返回类型应该是char**

您需要从while循环中删除index == 0条件,否则它将无法通过初始迭代。

此任务

res[index++]='';

应该是

res[index++]=NULL;

在将结果返回给调用者之前,您还需要调用free(command)。最后,您不应该在C.中投射malloc的结果

以下是您在修复上述问题后的代码:

char **read_command(char *text) {
int index=0;
char **res=NULL;
char *command= malloc(strlen(text)+1);
strcpy(command, text);
char *tok = strtok(command, " ");
while(tok!=NULL) {
res = realloc(res, sizeof(char*)*(index+1));
char *dup = malloc(strlen(tok)+1);
strcpy(dup, tok);
res[index++] = dup;
tok = strtok(NULL, " ");
}
// Need space to store the "terminating" NULL
// Thanks, BLUEPIXY, for pointing this out.
res = realloc(res, sizeof(char*)*(index+1));
res[index]=NULL;
free(command);
return res;
}

在ideone上演示。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **read_command(const char *text){
int index=0;
char **res=NULL;
char *command= malloc(strlen(text)+1);
strcpy(command, text+strspn(text, " tn"));//strspn for skip space from top
char *tok = strtok(command, " ");
res = realloc(res, sizeof(char*)*(index+1));
while(tok!=NULL){
res[index++] = tok;
res = realloc(res, sizeof(char*)*(index+1));
tok = strtok(NULL, " ");
}
res[index++]=NULL;
return res;
}
int main(void){
char *input="read A B C";
char **command = read_command(input);
int i;
for(i=0;command[i]!=NULL;++i){
printf("s[%d]=%sn", i, command[i]);
}
free(command[0]);//for free command of read_command
free(command);//for free res of read_command,,
return 0;
}

最新更新