c - 尝试将不规则数组传递给库 qsort 函数

标签 c qsort

有什么办法可以用不规则的数组来做到这一点吗?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/*function for use in built-in quick sort*/
static int compare(const void *x,const void *y){
    return strcmp(*(const char**)x, *(const char**)y);
}

int main(){
    FILE *p = fopen("file.txt","w");
    char ch = '\0',**c = (char**)calloc(6,sizeof(char*));
    int n[6]={0},i=0,j=0;
    fprintf(p,"jack\ndanny\njohn\nrachael\nrobin\ntom");
    fclose(p);
    p = fopen("file.txt","r");
    while(1){/*count number of char to create ragged array*/
        while((ch=getc(p))!= '\n'){
            if(ch == EOF) break;
            putchar(ch);
            n[i]++;
        }
        printf(" %d\n",n[i]);
        if(ch == EOF) break;
        ch = '\0';
        i++;
    }
    ch = '\0';
    for(i=0;i<6;i++)/*allocating memory*/
        c[i] = (char*) calloc(n[i],sizeof(char));
    fclose(p);
    i=0;
    p = fopen("file.txt","r");
    while(1){/*read from file to ragged array*/
        while((ch=getc(p))!= '\n'){
            if(ch == EOF) break;
            *(c[i]+j) = ch;
            j++;
        }
        i++;
        j = 0;
        if(ch == EOF) break;
        ch = '\0';
    }
    /*using built-in quick sort*/
    qsort(*c,6,sizeof(char*),compare);/*why won't this work?*/

    for(i=0;i<6;i++)
        printf("%s\n",*c[i]);
    return 0;
}

最佳答案

    for(i=0;i<6;i++)/*allocating memory*/
        c[i] = (char*) calloc(n[i],sizeof(char));

您还需要考虑每个字符串后面的 nul 终止符,这应该是

        c[i] = (char*) calloc(n[i] + 1,sizeof(char));

请记住,当您读回字符串时,您需要确保它们为空 也终止了。现在不需要,因为 calloc() 将确保您的最后一个字节 string 的值为 0,但通常需要注意。

    /*using built-in quick sort*/
    qsort(*c,6,sizeof(char*),compare);/*why won't this work?*/

取消引用 c 并将其传递给 qsort 将是错误的,它应该是正确的

    qsort(c,6,sizeof(char*),compare);

与 printf 相同, *c[i] 不是 printf %s 格式化程序所期望的 char * 。应该是

        printf("%s\n",c[i]);

关于c - 尝试将不规则数组传递给库 qsort 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18238190/

相关文章:

c - 在 C 中解析命令行参数

c - C语言返回指针的方法

c - 尝试使用 C qsort 函数时出现问题

c - 使用qsort和struct对列表进行排序

c - Qsort比较函数

c - 使用 qsort 按不同变量对结构指针进行排序

c++ - 标识符 "DDRB"未定义 - VS code/Visual studio

c - 使用 fgets 从文件中读取行并将每一行与 c 中的 strncmp 进行比较

c - 检测内核模块 netfilter hooking 中的数据包碎片

c - qsort在c中动态创建数组