简体   繁体   English

Qsort字符串数组按字母顺序排列

[英]Qsort array of strings in alphabetical order

Im trying to sort a array of strings I read from a file in alphabetical order using the qsort function. 我试图使用qsort函数对按字母顺序从文件中读取的字符串数组进行排序。 This is my code: 这是我的代码:

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

#define MAXCHAR 256


int main(int argc, char **argv){
    char tempList[MAXCHAR][MAXCHAR];
    char reader[MAXCHAR];
    FILE* fp;
    int i;
    char *n;
    int index = 0;
    if(argc != 2){
        printf("too few arguments\n");
        exit(-1);
    }

    fp=fopen(argv[1], "r");
    if(fp == NULL){
        printf("failed to open file\n");
        exit(-1);
    }
    while(!feof(fp)){
        fgets(reader, MAXCHAR, fp);
        n = strchr(reader, '\n');
        if(n != NULL){
            *n = '\0';
        }
        strcpy(tempList[index], reader);
        index++;
    }
    index--;
    for(i=0; i<index; i++){
        printf("%s\n", tempList[i]);

    }
    qsort(tempList, index, sizeof(char *), strcmp);

    for(i=0; i<index; i++){
        printf("%s\n", tempList[i]);
    }
}

When I run the program, the list doesn't get sorted at all. 当我运行程序时,列表根本没有排序。 I also tried methods posted on this website that asks a similar question and they all give me segmentation faults. 我也试过在这个网站上发布的方法,提出了类似的问题,他们都给我分段错误。 Is there something wrong with the code? 代码有问题吗?

Here is part of the content of the txt file. 这是txt文件内容的一部分。 It is a list of 40 names: 它是40个名字的列表:

Liam
Alexander
Mia
Noah
Emma
William
Charlotte
Charlotte
Mason
William
Ethan
Ethan
Liam
Alexander
Liam
Sophia
Emily
Mason
Alexander

You have a bona fide array of arrays; 你有一个真正的数组阵列; not an array of char* . 不是char*的数组。 Arrays aren't pointers. 数组不是指针。 qsort expects the stride of the elements in the sequence being sorted. qsort期望序列中元素的步幅被排序。 As your sequence is declared as: 当您的序列声明为:

char tempList[MAXCHAR][MAXCHAR];

the proper element size is the size of the inferior element size. 适当的元素大小是劣质元素大小的大小。 In this case you have an array of size MAXCHAR of array of char of size MAXCHAR (an array of arrays). 在这种情况下,必须大小的数组MAXCHAR的阵列的char尺寸的MAXCHAR (数组的数组)。

Thus this is wrong: 这是错误的:

qsort(tempList, index, sizeof(char *), strcmp);
// wrong size ==============^^^^

the size of each element should be: 每个元素的大小应该是:

qsort(tempList, index, sizeof tempList[0], strcmp);
// correct size ==============^^^^

The other issues in your program will eventually grief you and are covered in general comments below your question, but this is the fundamental problem preventing your sorting from working correctly. 您的程序中的其他问题最终会让您感到悲伤,并且在您的问题下面的一般注释中有所涉及,但这是阻止您的排序正常工作的根本问题。 A retooled version of your program appears below, addressing most of those concerns: 您的计划的重新编译版本如下所示,解决了大部分问题:

Updated Source 更新的来源

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

#define MAXCHAR 256

/* properly declared for compatibility with qsort */
static int cmp_str(const void *lhs, const void *rhs)
{
    return strcmp(lhs, rhs);
}

/* main entrypoint */
int main(int argc, char **argv)
{
    char tempList[MAXCHAR][MAXCHAR];
    FILE* fp;
    size_t i, index = 0;

    if(argc != 2)
    {
        printf("too few arguments\n");
        return EXIT_FAILURE;
    }

    fp=fopen(argv[1], "r");
    if(fp == NULL)
    {
        perror(argv[1]);
        return EXIT_FAILURE;
    }

    while(index < MAXCHAR && fgets(tempList[index], sizeof(*tempList), fp) != NULL)
    {
        char *n = strchr(tempList[index], '\n');
        if(n != NULL)
            *n = 0;
        if (*(tempList[index])) /* don't insert blank lines */
            ++index;
    }

    for(i=0; i<index; i++)
        printf("%s\n", tempList[i]);
    fputc('\n', stdout);


    qsort(tempList, index, sizeof tempList[0], cmp_str);

    for(i=0; i<index; i++)
        printf("%s\n", tempList[i]);

    return EXIT_SUCCESS;
}

Untested, but it should be pretty close. 未经测试,但它应该非常接近。

Best of luck. 祝你好运。

Your size value in qsort(tempList, index, sizeof(char *), strcmp); 您在qsort(tempList, index, sizeof(char *), strcmp);大小值qsort(tempList, index, sizeof(char *), strcmp); is wrong. 是错的。 It should be qsort(tempList, index, sizeof(*tempList), strcmp); 它应该是qsort(tempList, index, sizeof(*tempList), strcmp); .

I have tried to fix your code. 我试图修复你的代码。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//#include<io.h>    it's not standart


#define MAXCHAR 256

//  I implement the function because the warning is that
//  Incompatible pointer types passing 'int
//  (const char *, const char *)' to parameter of type
//  'int (*)(const void *, const void *)'

//  Already qsort() prototype is

// void qsort(void* ptr, size_t count, size_t size,
// int (*comp)(const void*, const void*));

// I think that the warning can be ignored strcmp also can be used

int myCompare(const void* a, const void* b)
{
    const char* aa = (const char*)a;
    const char* bb = (const char*)b;
    return strcmp(aa, bb);
}

int main(int argc, char **argv){
    char tempList[MAXCHAR][MAXCHAR];
    char reader[MAXCHAR];
    FILE* fp;
    int i;
    char *n;
    int index = 0;
    if(argc != 2){
        printf("too few arguments\n");
        exit(-1);
    }

    fp=fopen(argv[1], "r");
    if(fp == NULL){
        printf("failed to open file\n");
        exit(-1);
    }
    while(fgets(reader, MAXCHAR, fp) != NULL){ // !feof is not recommended search why

        n = strchr(reader, '\n');
        if(n != NULL){
            *n = '\0';
        }
        strcpy(tempList[index], reader);
        index++;
    }

    /*
    printf("%lu\n",sizeof(reader));     //256
    printf("%lu\n",sizeof(*reader));    //1
    printf("%lu\n",sizeof(*tempList));  //256
    printf("%lu\n",sizeof(**tempList)); //1
    */

    for(i=0; i<index; i++){
        printf("%s\n", tempList[i]);

    }
    qsort(tempList, index, sizeof(*tempList), myCompare);
    printf("\n\nAfter sorting\n\n");
    for(i=0; i<index; i++){
        printf("%s\n", tempList[i]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM