I need to sort an array of Strings in C. Here’s how I’m using the 2D Array:
I, first, declare the array of size 115 with each element of the array having a capacity of 10 characters:
char stock[115][10];
Then, as soon as the user enters a word that I need to put into this array, I store it like:
strcpy(stock[r],msg);
r++;
Where msg is the temporary variable used to store the user input and r is an integer initially assigned to 0.
Now the issue is when I need to print the Stock array. I need the output to be in a alphabetical order. I tried using qsort but could not get it to work, probably I didn’t quite implement it properly due to lack of understanding of qsort.
Please suggest a method to sort the STOCK array so that I can print the expected output.
Also note that the usual printing of Stock Array is working fine, ie, if i try to print the array in order in which it was stored, it works fine. It’s the sorting with which I need help.
Thanks 🙂
Edit01: The QSORT Method that I’m trying to use here is:
//Call Qsort Method
qsort(stock, r, sizeof(stock[0]), comp);
//Function to Compare two Strings - Used in the QSORT Method
int comp(const void *s1, const void *s2)
{
return (strcmp(*(char **)s1, *(char **)s2));
}
Here is the prototype of
qsort:baseis your array (stockhere).nmembis the number of members of your array (rhere).sizeis the size of an element (10here).The
comparfunction should compare two strings, and return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.strcmpcan do it for you.