qsort()函数在c中未按预期工作

qsort()函数在c中未按预期工作,c,qsort,C,Qsort,我正在尝试使用qsort()编写一个简单的字符串排序程序(灵感来自Linux中qsort手册中的程序) 这是我的密码 #include <stdio.h> #include <string.h> #include <stdlib.h> void disparray(int i,char words[10][20]); int compare_strings(const void *a,const void *b); int main() { int

我正在尝试使用qsort()编写一个简单的字符串排序程序(灵感来自Linux中qsort手册中的程序)

这是我的密码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void disparray(int i,char words[10][20]);
int compare_strings(const void *a,const void *b);

int main()
{
    int index=0;
    char words[10][20];
    while(fgets(words[index],20,stdin)) //take array of strings as input from stdin
    {
        if (words[index][0]=='\n') break;
        words[index][ strlen(words[index]) - 1 ] = '\0'; //to remove trailing newline
        index++;
        if (index==10)break;
    }
    disparray(index,words);
    qsort(words,index,sizeof(char*),compare_strings);
    disparray(index,words);
    return 0;
}

int compare_strings(const void *a,const void *b)
{
    //return strcmp(*(char **)a, *(char**)b); // this is what I think is correct command, but it causes segfault.
    return strcmp(a,b);                         // This gives wrong result.
}

void disparray(int index,char words[10][20])
{
    int f=0;
    while(f<index)
        {
            printf("%s\n",words[f]);
            f++;
        }
}
#包括
#包括
#包括
void disparray(int i,char字[10][20]);
int比较_字符串(const void*a,const void*b);
int main()
{
int指数=0;
字符字[10][20];
while(fgets(words[index],20,stdin))//从stdin获取字符串数组作为输入
{
如果(字[index][0]=='\n')中断;
words[index][strlen(words[index])-1]='\0';//删除尾随换行符
索引++;
如果(指数=10)中断;
}
disparray(索引、字);
qsort(单词、索引、大小(char*)、比较字符串);
disparray(索引、字);
返回0;
}
int比较_字符串(常量无效*a,常量无效*b)
{
//返回strcmp(*(char**)a,*(char**)b);//这是我认为正确的命令,但它会导致segfault。
返回strcmp(a,b);//这会给出错误的结果。
}
void disparray(整数索引,字符字[10][20])
{
int f=0;

而(fy您的项目大小,
sizeof(char*)
是错误的。您没有
char*
数组;您有
char[20]
(数组数组数组)。每个元素都是
char[20]
大小。试试
sizeof*words
。一个问题是数组中的元素的大小不是
char*
@WhozCraig,谢谢它工作。我之前试过19,但它必须是20。我认为它是19,因为数组中最大的char数将是19。你能把它作为一个答案写出来,让我接受它吗。OT:
strlen()-1
大多数情况下早晚都会进入desaster:运行程序并通过两次键入Ctrl-D(windows上的Ctrl-Z)终止输入(而不是按Enter键)。
./trial <words
one
two
three
four
five
six
seven
eight
nine
ten

0�one
three
four
five
six
seven
eight
nine
ten