将字符串拆分为C中的单词数组

时间:2016-09-06 21:07:47

标签: c arrays string split

我正在尝试创建一个将cstring拆分为单词数组的函数。例如。如果我发送“Hello world”,那么我会得到一个包含两个地方的数组,其中第一个地方的元素为“Hello”,第二个为“world”。我得到了分段错误,我不能为我的生活弄清楚什么似乎是错的。

  • 在for循环中,我正在检查有多少个空格,这决定了总共有多少个单词(空格总是N-1,N =单词的数量)。然后我告诉程序将1添加到计数器(因为N-1)。

  • 我声明了一个char * array [],以便将每个单词分开,不确定我是否需要在这里使用counter + 1(因为\ 0?)

  • 这是棘手的部分。我使用strtok分隔每个单词(使用“”)。然后我将mall * array []的每个位置malloc,以便它有足够的内存来存储单词。这样做直到没有更多的单词可以放入。

如果有人能给我一个部分导致分段错误的提示,我真的很感激!

void split(char* s){

    int counter = 0;
    int pos = 0;

    for(int i=0; s[i]!='\0'; i++){
        if(s[i] == ' '){
            counter ++;
        }
    }
    counter += 1;

    char* array[counter+1];

    char *token = strtok(s, " ");

    while(token != NULL){
        array[pos] = malloc(strlen(token));
        strcpy(array[pos], token);
        token = strtok(NULL, " ");
        pos++;
    }

1 个答案:

答案 0 :(得分:3)

  

如果我发送“Hello world”,那么我会得到一个有两个地方的数组   第一名有“Hello”元素,第二名是“world”。

没有。您不能将字符串文字传递给该函数。因为strtok()会修改其输入。因此,它将尝试修改字符串文字,从而产生undefined behaviour

请注意strtok()的限制。来自strtok()的手册页:

   Be cautious when using these functions.  If you do use them, note
   that:

   * These functions modify their first argument.

   * These functions cannot be used on constant strings.

   * The identity of the delimiting byte is lost.

   * The strtok() function uses a static buffer while parsing, so it's
     not thread safe.  Use strtok_r() if this matters to you.

因此,如果要使用strtok(),则需要将指针传递给可修改的内存位置。

正如BLUPIXY指出的那样,你的malloc()电话没有分配足够的空间。您需要比字符串长度多一个字节(对于终止的nul字节)。

相关问题