【发布时间】:2020-05-09 07:07:03
【问题描述】:
我对 C 非常陌生,我正在尝试将 qsort() 与 char 指针数组一起使用。它没有像我预期的那样按字母顺序对数组进行排序,它删除了第一个元素。我已经尝试调整所有参数,包括比较函数,但我无法找出问题所在。
输入单词:foo
输入单词:bar
输入单词:baz
输入单词:quux
预期:
酒吧
巴兹
富
昙花一现
结果:
酒吧
巴兹
昙花一现
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORDS 10
#define MAX_LENGTH 20
int read_line(char str[], int n);
int compare(const void *a, const void *b);
int main(void) {
char *words[MAX_WORDS], word[MAX_LENGTH + 1];
int i;
for(i = 0; i < MAX_WORDS; i++) {
printf("Enter word: ");
read_line(word, MAX_LENGTH);
words[i] = malloc(strlen(word) + 1);
if(!words[i]) {
printf("Allocation of memory failed...\n");
exit(EXIT_FAILURE);
}
strcpy(words[i], word);
if(!strlen(words[i]))
break;
}
qsort(words[0], i, sizeof(char *), compare);
for(int j = 0; j <= i; j++) {
printf("%s\n", words[j]);
}
return 0;
}
int read_line(char str[], int n) {
int ch, i;
while((ch = getchar()) != '\n') {
if(i < n)
str[i++] = ch;
}
str[i] = '\0';
return i;
}
int compare(const void *a, const void *b) {
return strcmp((char *) a, (char *) b);
}
【问题讨论】:
-
请不要编辑问题来解决问题,这是首先编写问题的原因。这使得整个问题和所有答案都毫无价值,因为如果不查看编辑历史,没有人可以看到问题。一个问题不应该是一个移动的目标。
-
@Gerhardh 知道了。
标签: c arrays sorting pointers quicksort