试图将不规则数组传递给库qsort函数

时间:2013-08-14 17:19:27

标签: 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;
}

1 个答案:

答案 0 :(得分:1)

    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]不是print *%格式化程序所期望的char *。它应该是

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