hi, i'm new to C and need to no can anyone help with a small problem.
wondering is it possible when im creating, a database system in C that can store information, can i make the information be stored alphabetically, and if so how do i go about it?
Printable View
hi, i'm new to C and need to no can anyone help with a small problem.
wondering is it possible when im creating, a database system in C that can store information, can i make the information be stored alphabetically, and if so how do i go about it?
I suspect qsort() is what you want.
how would i go about that? im pritty new to C and havent done qsort() before.
This came up on a board search, it's a wonderful thing, technology.
-PreludeCode:void sortarray ( double array1[], int num )
{
qsort ( array1, num, sizeof array1[0], cmp );
}
int cmp ( const void *x, const void *y )
{
if ( *(const double*)x < *(const double*)y )
return -1;
if ( *(const double*)x > *(const double*)y )
return 1;
return 0;
}
qsort() is found in stdlib.h. Its prototype is:
This may look intimidating, but it doesn't have to be. Let's take a look at each argument:Code:void qsort( void *base, size_t nel, size_t size, int (*compar)(const void *, const void *) );
Assuming you are comparing strings, you may either use strcmp() as your compare function or encapsulate it in your own function:
- base - The memory address of the list of items to sort. If your entries are in an array, simply put the array name here.
nel - The number of elements in your array.
size - The size of each element in the array (not the size of the entire array).
compar - The address of the function used to compare any two elements in your array.Here's a quick example:Code:int compare( void *a, void *b )
{
return ( strcmp(a,b) );
}
The output is:Code:#include <stdlib.h>
#include <stdio.h>
int compare( void *a, void *b )
{
return strcmp( a, b );
}
int main( void )
{
int i;
char array[5][10] = { "One", "Two", "Three", "Four", "Five" };
qsort( array, 5, 10, &compare );
for ( i=0; i<5; i++ )
printf( "%s\n", array[i] );
return 0;
}
- Five
Four
One
Three
Two