C中的三级间接char指针导致段错误

Three level indirection char pointer in C causes a segment fault

我在下面的注释包含大量等号的行中遇到段错误。

下面的函数str_spit,我写它是因为我想用一个特定的字符来分割一个字符串,比如逗号等

请帮忙。

 int str_split(char *a_str, const char delim, char *** result)
    {
       int word_length = 0;
       int cur_cursor = 0;
       int last_cursor = -1;
       int e_count = 0;
       *result = (char **)malloc(6 * sizeof(char *));
       char *char_element_pos = a_str;
       while (*char_element_pos != '[=10=]') {
        if (*char_element_pos == delim) {
            char *temp_word =   malloc((word_length + 1) * sizeof(char));

            int i = 0;
            for (i = 0; i < word_length; i++) {
                temp_word[i] = a_str[last_cursor + 1 + i];
            }

            temp_word[word_length] = '[=10=]';
            //
            *result[e_count] = temp_word;//==============this line goes wrong :(
            e_count++;
            last_cursor = cur_cursor;
            word_length = 0;
        }
        else {
            word_length++;
        }
        cur_cursor++;
        char_element_pos++;
    }
    char *temp_word = (char *) malloc((word_length + 1) * sizeof(char));
    int i = 0;
    for (i = 0; i < word_length; i++) {
        temp_word[i] = a_str[last_cursor + 1 + i];
    }
    temp_word[word_length] = '[=10=]';
    *result[e_count] = temp_word;
    return e_count + 1;
  }

   //this is my caller function====================
  int teststr_split() {
    char delim = ',';
    char *testStr;
    testStr = (char *) "abc,cde,fgh,klj,asdfasd,3234,adfk,ad9";

    char **result;

    int length = str_split(testStr, delim, &result);
    if (length < 0) {
        printf("allocate memroy failed ,error code is:%d", length);
        exit(-1);
    }
      free(result);
      return 0;
    }

我想你是说

( *result )[e_count] = temp_word;//

而不是

*result[e_count] = temp_word;//

只有当e_count等于0时,这两个表达式才等价。:)

[] 的优先级高于 *,因此括号可能会解决这个问题:

(*result)[e_count] = temp_word;

我没有检查代码中的更多问题。提示:strtok() 可能会很好地完成您的工作。