This program so far has one purpose, take in two integers(the size of the user defined arrays) and then takes in one element or character at a time and adds them to the array. Once both arrays are filled, one of the arrays must be alphabetized (I’m attempting to do this with the built in ‘qsort’).
However, this code hits a runtime error once the qsort is called, and my problem is I don’t know why or how to fix it.
My Code:
#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;
}
XSequenceis just a char-pointer, so you need only a straight cast:Or simply:
Your code would work if you passed it
&XSequence, but there’s no need for the extra indirection.You also need to pass
sizeof(char), or just1, as the element size. You are not sorting pointers, but actual characters!(I think this is classical case of “overthinking it”. Your actual scenario is a classic, on-the-nose use case for
qsort, and you made it way more complicated than it is.)