-1

到目前为止,这个程序有一个目的,接受两个整数(用户定义数组的大小),然后一次接受一个元素或字符并将它们添加到数组中。一旦两个数组都被填满,其中一个数组必须按字母顺序排列(我正在尝试使用内置的“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; 
}
4

2 回答 2

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

sizeof(char*)作为元素大小传递,但Xsequence它是一个数组char,而不是char*. 你应该通过sizeof(char)

于 2012-02-13T06:08:40.087 回答
0

XSequence只是一个字符指针,所以你只需要一个直接的演员:

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

或者简单地说:

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

如果您通过它,您的代码将起作用&XSequence,但不需要额外的间接。

您还需要传递sizeof(char),或者只是1,作为元素大小。您不是对指针进行排序,而是对实际字符进行排序!

(我认为这是“过度思考”的经典案例。你的实际场景是一个经典的、直接的用例qsort,你让它变得比它更复杂。)

于 2012-02-13T06:02:47.233 回答