How to use qsort for an array of strings?

我们两清 提交于 2019-12-19 10:26:29

问题


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

int sortstring(const void *str1, const void *str2) {
    const char *rec1 = str1;
    const char *rec2 = str2;
}

void sortutil(char* lines[]) {
    qsort(lines, 200, sizeof(char), sortstring);
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "sortutil.h"

int getarray(char *lines[]) {
    int i = 0;
    char *text = (char *)malloc(200);
    while (fgets(text, 200, stdin) != NULL) {
        lines[i] = text;
        i++;
        text = (char *)malloc(200);
    }
    return i;
}

void printarray(char *lines[], int max) {
    for (int i = 0; i < max; i++)
        printf("%s\n\n", lines[i]);
}

int main(int argc, char* argv[]) {
    char* arr[100];
    int numlines = getarray(arr);
    printf("There are %d lines\n", numlines);
    printarray(arr, numlines);

    for (int i = 1; i < argc;  i++) {
        if (strcmp(argv[i], "-s") == 0) {
            sortutil(arr);
            printarray(arr, numlines);
        }
    }
}

When I send in a file with arbitrary text, It'll read the file and print it out, but when i call -s and call the qsort function, it comes back with nulls. I'm sure I am using qsort incorrectly, what is the right way to use it for an array to char pointers?


回答1:


Your comparator is being sent each pair by-address. I.e. they're pointer-to-pointer-to-char.

Change the comparator to:

int sortstring( const void *str1, const void *str2 )
{
    char *const *pp1 = str1;
    char *const *pp2 = str2;
    return strcmp(*pp1, *pp2);
}

Likewise, your sortutil needs to know the number of items being sorted, as well as pass the correct size of each item. Change that to:

void sortutil(char* lines[], int count)
{
    qsort(lines, count, sizeof(*lines), sortstring);
}

Finally, the call from main() should look like this:

sortutil(arr, numlines);

That should do it.




回答2:


What the compar function gets are pointers to the elements in your array, which in this case, are pointers to char. So the parameters str1 and str2 are actually pointers to pointers to char. You must cast them like this:

int sortstring( const void *str1, const void *str2 )
{
    const char *rec1 = *(char**)str1;
    const char *rec2 = *(char**)str2;
    int val = strcmp(rec1, rec2);

    return val;
}

Then you have to use the proper element size in qsort.

qsort(lines, 200, sizeof(char*), sortstring);



回答3:


This line is incorrect.

    qsort(lines, 200, sizeof(char), sortstring);

Change it to

    qsort(lines, 200, sizeof(char*), sortstring);


来源:https://stackoverflow.com/questions/23189630/how-to-use-qsort-for-an-array-of-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!