如何对字符串数组使用 qsort?

Jak*_*han 2 c string qsort

#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);
}
Run Code Online (Sandbox Code Playgroud)
#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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我发送带有任意文本的文件时,它会读取该文件并将其打印出来,但是当我调用 -s 并调用该qsort函数时,它会返回空值。我确信我正在使用qsort incorrectly,将其用于数组到 char 指针的正确方法是什么?

Who*_*aig 9

您的比较器将按地址每对发送。即它们是指针到指针到字符。

将比较器更改为:

int sortstring( const void *str1, const void *str2 )
{
    char *const *pp1 = str1;
    char *const *pp2 = str2;
    return strcmp(*pp1, *pp2);
}
Run Code Online (Sandbox Code Playgroud)

同样,您sortutil需要知道正在排序的项目数量,以及传递每个项目的正确大小。将其更改为:

void sortutil(char* lines[], int count)
{
    qsort(lines, count, sizeof(*lines), sortstring);
}
Run Code Online (Sandbox Code Playgroud)

最后,来自的调用main()应如下所示:

sortutil(arr, numlines);
Run Code Online (Sandbox Code Playgroud)

应该可以做到这一点。