#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);
}
}
}
当我发送一个包含任意文本的文件时,它会读取文件并将其打印出来,但是当我调用 -s 并调用 qsort
函数时,它会返回空值。我确定我使用的 qsort 不正确
,将它用于数组到 char 指针的正确方法是什么?
最佳答案
您的比较器每对按地址发送。 IE。它们是指向字符的指针。
将比较器更改为:
int sortstring( const void *str1, const void *str2 )
{
char *const *pp1 = str1;
char *const *pp2 = str2;
return strcmp(*pp1, *pp2);
}
同样,您的 sortutil
需要知道要排序的项目数,并传递每个项目的正确大小。将其更改为:
void sortutil(char* lines[], int count)
{
qsort(lines, count, sizeof(*lines), sortstring);
}
最后,main()
的调用应该如下所示:
sortutil(arr, numlines);
应该这样做。
关于c - 如何对字符串数组使用 qsort?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23189630/