使用qsort对c中的malloced字符数组进行排序

时间:2012-02-13 05:55:58

标签: c qsort

到目前为止,这个程序有一个目的,接受两个整数(用户定义数组的大小),然后一次接收一个元素或字符并将它们添加到数组中。一旦两个数组都被填充,其中一个数组必须按字母顺序排列(我试图用内置的'qsort'来做这个)。

但是,一旦调用qsort,此代码就会遇到运行时错误,我的问题是我不知道为什么或如何修复它。

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int toExit(int exit){
    while(exit != 1 || exit !=2){

        printf("\n\nPlease Choose:\n1) Exit\n2) Run program again\nYour choice: ");
        scanf("%d", &exit);
        printf("\n");

        switch(exit){
        case 1:
            return exit;
        case 2:
            return exit;
        default:
            printf("That is not one of the given options.\n\n");
        }
    }

}    

int compare(const void *a, const void *b){

    const char* a1 = *(const char**)a;
    const char* b1 = *(const char**)b;
    return strcmp(a1,b1);
}  

int main(void) {

    int exit=0, i, j;
    int lengthX, lengthA;
    char *Xsequence, *Asequence, *_$;

    while(exit != 1){


    printf("please enter the length of sequence A: ");
    scanf("%d", &lengthA);
    printf("please enter the length of sequence X: ");
    scanf("%d", &lengthX);

    printf("\n");  //spacing, visual look of the program

    Asequence =(char*) malloc(lengthA*sizeof(char));
    Xsequence =(char*) malloc(lengthX*sizeof(char));

    for(j=0;j<=lengthA-1;j++)
    {
        printf("Element %d of A: ",j+1);
        scanf("%s", &Asequence[j]);
    }

    printf("Last Element of A (looking for \"$\"): ");
    scanf("%s", &_$);
    printf("\n");  //spacing, visual look of the program

    for(j=0;j<=lengthX-1;j++)
    {
        printf("Element %d of X: ",j+1);
        scanf("%s", &Xsequence[j]);
    }

    printf("Last Element of X (looking for \"$\"): ");
    scanf("%s", &_$);
    printf("\n");  //spacing, visual look of the program

    qsort (Xsequence, lengthX, sizeof(char*), compare);
    printf("The \"A\" sequence is: %s\n",Asequence);
    printf("The \"X\" sequence is: %s\n",Xsequence);


    exit = toExit(exit);

    }
// return 0; 
}

2 个答案:

答案 0 :(得分:0)

XSequence只是一个char-pointer,所以你只需要一个直接的演员:

const char * a1 = (const char *) a;
const char * b1 = (const char *) b;

或者简单地说:

return strcmp((const char *) a, (const char *) b);

如果你传递了{/ 1>},你的代码就会起作用,但不需要额外的间接代码。

您还需要传递&XSequencesizeof(char)作为元素大小。你没有排序指针,而是实际的字符!

(我认为这是“过度思考”的经典案例。你的实际场景是1的一个经典的鼻子用例,你让它变得比它更复杂。)< / p>

答案 1 :(得分:0)

qsort (Xsequence, lengthX, sizeof(char*), compare);

您传递sizeof(char*)作为元素大小,但Xsequencechar的数组,而不是char*。您应该改为sizeof(char)