You either use the qsort function provided by the standard library, or you use your own function (e. The basic declaration for qsort is: void qsort (void *base, size. Note: your compare function takes 2 generic pointers (void type) as its input. C Examples Arrays Strings Algorithms Sort an array of strings in C This example program demonstrates sorting an array using qsort. This C Program sorts array in an ascending order. Here is source code of the C program to sort the array in an ascending order. The C program is successfully compiled and run on a Linux system. The program output is also shown below. For sorting characters, you correctly recognize you will sort by the ascii values. Therefore, all your compare function needs to do is return whether of the two characters: (a) one is greater than the other, or (b) they are equal. An example of the compare function here would be: int compare. In the compare function, since you are passed a pointer to type void, you need to cast it to your type before you can dereference it to get the value at the pointer address. Here casting the void * to char * is all you need. Then you need to dereference it with '*' before you making the comparison. Putting it all together in a short example: #include < stdio. MAXS 3. 2. /* simple compare function for qsort, returns. This also provides a good look at the way you approach using qsort. Above, in the first example, when we approached using qsort, we had to answer the question: . How are strings referenced? Through a pointer to the beginning character in the string. So here, instead of sorting each char in an array of chars, we will be sorting stringsin an array of strings (or properly an array of pointers to type char *) As far is qsort is concerned, the only difference will be the compare function (and the input..). We need to sort strings, so the compare function must provide a way of comparing strings. In C, the standard string comparison function is strcmp (or strncmp to limit the number of characters compared). For instance, using strcmp to sort an array of strings, you would use something similar to: /* string compare function */. Basically, changing only the compare function (and the input), you can then use qsort to sort your array of strings, as follows: #include < stdio.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
January 2017
Categories |