簡體   English   中英

試圖將衣衫array的數組傳遞給庫qsort函數

[英]Trying to pass ragged array to library qsort function

有什么辦法可以用破爛的數組嗎?

#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()將確保字符串中的最后一個字節的值為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]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM