所以我搜索了这个论坛,回过头来阅读本章中关于使用qsort()
的每一个细节,但我似乎无法解决这个问题。当我运行我的代码时,它每次都会崩溃,我尝试使用我可能找到的每种不同的方法进行投射,但我却无法让它停止崩溃。
char *line[MAX_WORDS] <- This is my array I am trying to sort
qsort(line, word_count, sizeof(char*), compare_words);
int compare_words(const void *p, const void *q)
{
const char *p1 = *(char**)p;
const char *q1 = *(char**)q;
return strcmp(p1, q1);
}
这是完整的源代码
//第17章编程项目#6 //第17章编程项目#5
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_LEN 20
#define MAX_WORDS 10
int read_line(char str[], int n);
int compare_words(const void *p, const void *q);
int main(void)
{
char *line[MAX_WORDS], word_str[MAX_WORD_LEN];
int i = 0, word_count = 0;
for (;;) {
printf("Enter word: ");
read_line(word_str, MAX_WORD_LEN);
if (strlen(word_str) == 0)
break;
line[i] = malloc(strlen(word_str));
if (line[i] == NULL) {
printf("-- No space left --\n");
break;
}
strcpy(line[i], word_str);
word_count++;
}
printf("Word_count: %d\n", word_count);
qsort(line, word_count, sizeof(char*), compare_words);
printf("\nIn sorted order:");
for (i = 0; i <= word_count - 1; i++)
printf(" %s", line[i]);
putchar('\n');
return 0;
}
int read_line(char str[], int n)
{
int ch, i = 0;
while ((ch = getchar()) != '\n')
if (i < n)
str[i++] = ch;
str[i] = '\0';
return i;
}
int compare_words(const void *p, const void *q)
{
const char *p1 = *(char**)p;
const char *q1 = *(char**)q;
return strcmp(p1, q1);
}
答案 0 :(得分:1)
你正在超越一些缓冲区:
line[i] = malloc(strlen(word_str));
// ...
strcpy(line[i], word_str);
您需要通过以下方式为终止'\0'
字符添加空格:
line[i] = malloc(strlen(word_str) + 1);
// ...
strcpy(line[i], word_str);
或
line[i] = strdup(word_str);
if (line[i] == NULL) {
printf("-- No space left --\n");
break;
}
在阅读单词时,您永远不会递增i
,因此word_count
或5
处有line[0]
,但所有单词都由{{临时指向} 1}};其余的(line[1]..line[4]
)未初始化。
将您的第一个for
循环更改为:
for ( i = 0; i < MAX_WORDS; ++i ) {
// ..
}