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

时间:2013-12-29 12:47:08

标签: c strtok

我失去了理智。 我想用空格分割字符串(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;
}

来自main方法

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

谢谢

2 个答案:

答案 0 :(得分:1)

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

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

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

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

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

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

此作业

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;
}

Demo on ideone.

答案 1 :(得分:0)

#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, " \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 A B C";
    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;
}