简体   繁体   中英

How to use qsort for an array of strings?

#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?

Your comparator is being sent each pair by-address. Ie 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.

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);

This line is incorrect.

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

Change it to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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