卡住!.. 分段错误、qsort_r、数组、指针的混合

Stuck!.. a mix of segmentation fault, qsort_r, arrays, pointers

我希望我在下面说得简短清楚我想做什么。

代码对于 SOF 问题来说相当复杂,我不认为我可以让它更简单,同时让其他人可以直接测试它。

所以我把相关的部分剪下来放在这里

为什么我会收到这个错误,你能帮我解决吗?

感谢任何帮助!

谢谢。

    char words[100][WORD_LENGTH];

    char temp[WORD_LENGTH];

    // scan the next %s from stream and put it to temp
    while(fscanf(file, "%s", temp) > 0){
        // printf("reducer reads: %s\n", temp);

        strcpy(words[arr_i], temp);
        printf("%d -- %s\n", arr_i, words[arr_i]);

        arr_i++;

    }

在第二行我收到分段错误。 (并可能与 valgrind 一起泄漏)

    int thunk = WORD_LENGTH; 
    qsort_r(&words, sizeof(words)/sizeof(words[0]), sizeof(words[0]), cmpstringp, &thunk);

来自 "man qsort":

static int cmpstringp(const void *p1, const void *p2) {
   /* The actual arguments to this function are "pointers to
      pointers to char", but strcmp(3) arguments are "pointers
      to char", hence the following cast plus dereference */

   return strcmp(* (char * const *) p1, * (char * const *) p2);
}

根据man qsort

The qsort_r() function is identical to qsort() except that the comparison function compar takes a third argument

你的比较函数有两个参数。

更新:真正的崩溃原因如下。您正在传递给 char[WORD_LENGTH] 类型数组的比较函数元素,而不是 man qsort 示例中的 char*。所以传递给比较函数的参数是p1 = &words[_],它是一个指向要比较的字符串的指针。而在 char 指针的情况下,它将是 (char **),只是指向 char/string 指针的指针。因此,strcmp(* (char * const *) p1, * (char * const *) p2); 行中的强制转换是不必要且有害的,因为在您的情况下,最左边的取消引用是问题的原因。删除它们,只留下 strcmp(p1, p2)
作为旁注,这个问题再次强调了字符串数组声明为 char *[]char [][].

之间的区别