0

有没有办法用一个参差不齐的数组来做到这一点?

#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;
}
4

1 回答 1

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

请记住,当您回读字符串时,您需要确保它们也被 nul 终止。现在不需要它,因为 calloc() 将确保字符串中的最后一个字节是值 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] 不是 char * 就像 printf %s 格式化程序所期望的那样。它应该是

        printf("%s\n",c[i]);
于 2013-08-14T18:28:14.750 回答