2017-08-17 66 views
2

我需要拆分一個字符串,其中有空格(例如,字符串:Hello this is an example string.)成一個單詞數組。我不確定我在這裏錯過了什麼,我也很好奇以什麼來測試這個功能最好的辦法是,唯一允許的庫函數是mallocC - 在空白處拆分一個字符串

任何幫助表示讚賞!

#include <stdlib.h> 

char **ft_split(char *str) { 
    int wordlength; 
    int wordcount; 
    char **wordbank; 
    int i; 
    int current; 

    current = 0; 
    wordlength = 0; 
    //while sentence 
    while (str[wordlength] != '\0') { 
     //go till letters 
     while (str[current] == ' ') 
      current++; 
     //go till spaces 
     wordlength = 0; 
     while (str[wordlength] != ' ' && str[wordlength] != '\0') 
      wordlength++; 
     //make memory for word 
     wordbank[wordcount] = malloc(sizeof(char) * (wordlength - current + 1)); 

     i = 0; 
     //fill wordbank current 
     while (i < wordlength - current) { 
      wordbank[wordcount][i] = str[current]; 
      i++; 
      current++; 
     } 

     //end word with '\0' 
     wordbank[wordcount][i] = '\0'; 

     wordcount++; 
    } 
    return wordbank; 
} 
+0

你爲什麼不使用',和strchr()'? –

+0

或'strtok_s' /'strtok_r'? – Useless

+2

你現在在做「魚」嗎? – Gam

回答

1

您需要malloc()的Wordbank了。你可以指望的數量的話,然後

wordbank = malloc((count + 1) * sizeof(*wordbank)); 
if (wordbank == NULL) 
    return NULL; 

備註sizeof(char)是1的定義。而sizeof *pointer永遠是你想要的。

+0

是的,這個'sizeof(* pointer)'技巧看起來很酷,而且我已經看到人們以你的方式向其他人推薦它,但是如何解引用一個未初始化的指針呢?據我所知,這是未定義的行爲...... – ForceBru

+0

@ForceBru當不需要時,sizeof'不會計算參數。看到[DEMO](http://ideone.com/ASzi4X) – BLUEPIXY

+0

@BLUEPIXY,實際上,這確實很聰明。謝謝! – ForceBru

1

有你的代碼中的多個問題:

  • 你不分配一個數組wordbank指向,訪問一個未初始化的指針是未定義行爲。
  • 您的掃描字符串的方法被破壞:您在循環內重置wordlength,以便從字符串的開始處繼續重新掃描。
  • 您應該在數組中爲尾部空指針分配一個額外的條目,以指示數組的末尾指向調用者。

下面是修改後的版本:

#include <stdlib.h> 

char **ft_split(const char *str) { 
    size_t i, j, k, wordcount; 
    char **wordbank; 

    // count the number of words: 
    wordcount = 0; 
    for (i = 0; str[i]; i++) { 
     if (str[i] != ' ' && (i == 0 || str[i - 1] == ' ')) { 
      wordcount++; 
     } 
    } 

    // allocate the word array 
    wordbank = malloc((wordcount + 1) * sizeof(*wordbank)); 
    if (wordbank) { 
     for (i = k = 0;;) { 
      // skip spaces 
      while (str[i] == ' ') 
       i++; 
      // check for end of string 
      if (str[i] == '\0') 
       break; 
      // scan for end of word 
      for (j = i++; str[i] != '\0' && str[i] != ' '; i++) 
       continue; 
      // allocate space for word copy 
      wordbank[k] = p = malloc(i - j + 1); 
      if (p == NULL) { 
       // allocation failed: free and return NULL 
       while (k-- > 0) { 
        free(wordbank[k]); 
       } 
       free(wordbank); 
       return NULL; 
      } 
      // copy string contents 
      memcpy(p, str + j, i - j); 
      p[i - j] = '\0'; 
     } 
     // set a null pointer at the end of the array 
     wordbank[k] = NULL; 
    } 
    return wordbank; 
}