到目前为止,该程序只有一个目的,接收两个整数(用户定义数组的大小),然后一次接收一个元素或字符并将它们添加到数组中。一旦两个数组都填满,其中一个数组必须按字母顺序排列(我正在尝试使用内置的“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;
}
最佳答案
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
的一个经典的、直观的用例,并且您使它比实际情况更加复杂.)
关于c - 使用 qsort 对 c 中分配的字符数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9256192/