I'm trying to sort an array of structs using selection sort and pointers, but I'm having some trouble.
When I try to print the array out to see if the names are sorted, all the names are sorted except for the one in the first position which remains where it is (unsorted).
/*
all is the unordered array of struct; pLast is pointer to the last struct in array.
*/
void sortArray(CASE* all, CASE* pLast)
{
CASE* current;
CASE* walker;
CASE* smallest;
CASE temp;
for(current = all; current < pLast; current++)
{
smallest = current;
for (walker = current + 1; walker <= pLast; walker++)
{
if(strcmp(walker->name, smallest->name) < 0 )
smallest = walker;
}
temp = *current;
*current = *smallest;
*smallest = temp;
}
for(walker = all; walker <= pLast; walker++)
{
printf("%s\n", walker->name);
}
return;
}
Any tips?
Thanks
Edit: major revision that allows the names to be printed, but not fully sorted
smallestbefore you use it. The first time your loop runs, it will have some random pointer value which you are dereferencing withsmallest->name. As soon as you do that, who knows what'll happen?smallestitem, but no outer loop.smallestwithwalker. However, after the inner loop has finished,walkeris a pointer to the next CASE after the end of the array -- i.e.walker == pLast + 1is true -- and that's a bad pointer to memory you probably don't own. Hence the segmentation fault. (FYI en.wikipedia.org/wiki/Segmentation_fault)