【发布时间】:2012-02-13 05:55:57
【问题描述】:
到目前为止,这个程序只有一个目的,接受两个整数(用户定义数组的大小),然后一次接受一个元素或字符并将它们添加到数组中。一旦两个数组都被填满,其中一个数组必须按字母顺序排列(我正在尝试使用内置的“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;
}
【问题讨论】:
-
首先,在 C 语言中,我强烈建议不要转换
malloc的返回值(或任何其他隐式void *指针转换)。 -
顺便说一句,为什么不调用
free()释放分配的内存? -
php-coder,因为程序结束了?
-
我建议从启用所有警告开始并修复它们。之后处理以下内存问题: Asequence 和 Xsequence 不是以 null 结尾的,因此您不能使用 strcmp(),因为函数需要以 null 结尾的字符串。因此,您应该在每个字符串的末尾添加 \0,或者使用 strncmp() 代替。
-
@Joey:啊,“世界末日编程范式”的另一个很好的例子:-)