I am using the built in qsort to sort an array of structs. But after the call to qsort the last element in the array seems to have had its value that I am sorting by set to empty.
Here is my code…
int numEntries = 5;
TvEntry* entries[numEntries]; //create array
//Entries get added to the array here...
qsort( *entries, numEntries, sizeof(TvEntry*), &compareByName ); //sort
displayAll( entries, numEntries ); //display
//here is my sort method
int compareByName( const void* val1, const void* val2 )
{
const TvEntry* entry1 = (TvEntry*)val1;
const TvEntry* entry2 = (TvEntry*)val2;
return strcasecmp( entry1->title, entry2->title );
}
//here is my display method
void displayAll( TvEntry* entries[], int length )
{
if( entries == NULL )
{
printf( "List is empty\n" );
}
else
{
int i = 0;
for( i = 0; i < length; i++ )
{
printf( "ENTRY: %s\n", entries[i]->title );
}
}
}
I should mention that if i comment out the line which calls qsort then all entries are displayed correctly but when qsort is called then the entries are all displayed (Not Sorted) and printing a blank value for title for the last entry.
is wrong, you don’t want to dereference the first element of your array. Make it
Furthermore, your compare funciton will receive pointers to the elements, and the elements are pointers, so it should be e.g.