【发布时间】:2014-06-05 13:42:58
【问题描述】:
所以我搜索了这个论坛,然后回来阅读本章中关于使用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);
}
【问题讨论】:
-
@Jon 排序一个指向字符串的指针数组
-
数组是否包含
word_count有效字符串?如果您遍历第一个word_count条目并打印它们,它是否正常工作? -
你确定
word_count <= MAX_WORDS? -
工作正常,如图所示,给定有效的
word_count和有效的line内容:ideone.com/qPDpqt -
是的,我测试了 word_count,当我输入 2 个单词时,它会打印 2