将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++]='\0'; return res; } 

从主要方法

 char *input="read ABC"; char *command = read_command(input); 

谢谢

您使用错误的类型来计算此调用中的大小:

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

你需要使用char* ,而不是char ,使用sizeof ,如下所示:

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

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

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

这个任务

 res[index++]='\0'; 

应该

 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  #include  #include  char **read_command(const char *text){ int index=0; char **res=NULL; char *command= malloc(strlen(text)+1); strcpy(command, text+strspn(text, " \t\n"));//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 ABC"; char **command = read_command(input); int i; for(i=0;command[i]!=NULL;++i){ printf("s[%d]=%s\n", i, command[i]); } free(command[0]);//for free command of read_command free(command);//for free res of read_command,, return 0; }