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));
}
qsort
is your friend. Post yourqsort
code perhaps? – William Morris Oct 24 '12 at 13:50sizeof(stock[0])
instead of hard coding the value. I liked this approach. I am learning C and your example set the standards for me to look at. BRILLIANT :-) – nIcE cOw Oct 24 '12 at 14:05