mms*_*swe 2 c arrays pointers memory-leaks qsort
我希望我简短地说清楚我在下面要做的事情.
对于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++;
}
Run Code Online (Sandbox Code Playgroud)
在第二行我得到分段错误错误.(可能与valgrind泄漏)
int thunk = WORD_LENGTH;
qsort_r(&words, sizeof(words)/sizeof(words[0]), sizeof(words[0]), cmpstringp, &thunk);
Run Code Online (Sandbox Code Playgroud)
来自"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);
}
Run Code Online (Sandbox Code Playgroud)
按照man qsort:
qsort_r()函数与qsort()相同,除了比较函数compar采用第三个参数
你的比较函数有两个参数.
更新:真正的崩溃原因如下.要传递到类型的阵列的比较功能元件char[WORD_LENGTH],而不是char*如在man qsort实施例.因此传递给比较函数的参数是p1 =&words [_],它是指向要比较的字符串的指针.在char指针的情况下,它(char **)只是一个指向char/ string指针的指针.所以线上的演员strcmp(* (char * const *) p1, * (char * const *) p2);是不必要和有害的,因为在你的情况下,最左边的解引用是问题的原因.删除它们然后离开strcmp(p1, p2).
作为旁注,这个问题再次强调字符串数组声明与char *[]和之间的区别char [][].