Domanda

Is there any way to do this with a ragged array?

#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;
}
È stato utile?

Soluzione

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

You need to account for the nul terminator after each string too, this should be

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

Keep in mind that when you read the strings back, you need to ensure they are nul terminated too. It's not needed now, since calloc() will ensure the last byte in your string is the value 0, but generally something to be aware of.

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

Dereferencing c and passing it to qsort will just be wrong, it should be just

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

Same thing with the printf , *c[i] is not a char * as the printf %s formatter will expect. It should be

        printf("%s\n",c[i]);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top