The prompt here was for us to use qsort() and bsearch() to find and return the element that the user specified. So if an array had elements [blue, red, green, orange, ...] and the user entered "red", I am to use bsearch() to traverse the list and return the element they selected.
To do so I have done this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// ------------- Comparative Function ---------------
int compareSort(const void * First, const void * Next) {
return (*(int*)First - *(int*)Next);
}
int main() {
char sixteenColors[5][10] = { "black", "blue", "green", "cyan", "red" };
char colorName[100];
printf("\nEnter a desired color name: "); // prompt user for input
gets(colorName); // get input
printf("\n\nYou chose the color: %s", colorName); // display choice
char *item; // create pointer to catch bsearch() result
int n;
printf("\nBefore sorting the list is: ");
for (n = 0; n < 5; n++) { // traverse through list and print all elements
printf("%s ", sixteenColors[n]); // print all in list as is
}
qsort(sixteenColors, 5, sizeof(char), compareSort); // call qsort() and pass in all paramenters
printf("\nAfter sorting the list is: \n");
for (n = 0; n < 5; n++) { // 'for' loop for printing
printf("%s ", sixteenColors[n]); // print newly sorted array
}
/* using bsearch() to find the specified color in the array */
item = (char*)bsearch(&colorName, sixteenColors, 5, sizeof(char), compareSort);
if (item != NULL) {
printf("\nFound item = %d\n", *item); // if present print what was found
}
else {
printf("Item = %d could not be found\n", *item); // print error message of no element found
}
return(0);
}
which has worked for me in the past when trying this program out with integers; but now that I'm attempting to do this with char[] (or strings) I am running into more issues that I am unequipped to answer...
This is the output I get when I try to run this:
Enter a desired color name: red
You chose the color: red
Before sorting the list is: black blue green cyan red
After sorting the list is: backl blue green cyan red
And it gets this far before getting the error message of "Exception thrown: read access violation. item was nullptr" ......
so I tried to rearrange my list to see how the sorting went with a different order, and this is what I got:
Enter a desired color name: red
You chose the color: red
Before sorting the list is: red green blue cyan black
After sorting the list is: green blue cyan black
Please let me know if you can solve this or help me do so.