【问题标题】:Three level indirection char pointer in C causes a segment faultC中的三级间接char指针导致段错误
【发布时间】:2015-09-25 07:05:45
【问题描述】:

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

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 != '\0') {
        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] = '\0';
            //
            *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] = '\0';
    *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;
    }

【问题讨论】:

  • 作为初学者,您应该从一星和两星开始,然后再成为三星程序员(如果这确实是您想要/需要的)。
  • 标准警告:不要像malloc返回的那样转换void *
  • str_spit 在这里确实是一个完美的命名scnr

标签: c segmentation-fault segment


【解决方案1】:

我想你是说

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

而不是

*result[e_count] = temp_word;//

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

【讨论】:

    【解决方案2】:

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

    (*result)[e_count] = temp_word;
    

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

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多