[cs631apue] Trouble sorting with qsort

Tejas Nadkarni tnadkarn at stevens.edu
Sat Sep 21 15:14:43 EDT 2013


Nevermind, solved it :)

I moved the strcmp into a separate function and provided that to quicksort
and it appears to work. My compare

int cmp (char **str1, char **str2)
{
  return strcmp(*str1,*str2);
}


On Sat, Sep 21, 2013 at 2:47 PM, Tejas Nadkarni <tnadkarn at stevens.edu>wrote:

> It might be a stupid mistake but I'm puzzled. I'm trying to sort an array
> of strings which is the file listing for a directory. Based on manpages,
> online docs and forums I'm using the write code and it executes without
> errors. However the resulting array is not sorted properly. qsort is a void
> function so no way to tell if it's erroring out during the sort.
>
> Here's my call
>
> qsort(input, size, sizeof(char*), (int(*)(const void*, const
> void*))strcmp);
>
> input is my char* array, size is the # of elements in input, sizeof(char*)
> size of each element, the last parameter is casting strcmp for const void
> since that's what's needed by qsort. I've also tried writing my own compare
> function with strcmp in it and I get same results.
>
> It's quite puzzling.
>
> Here's an example output before and after qsort by running ls on /sys on
> Ubuntu so it's doing something but almost like it's not completing the
> sort?? Any ideas?
>
> $ ./ls /sys
> fs
> devices
> dev
> bus
> class
> firmware
> hypervisor
> kernel
> power
> module
> block
>
>
> firmware
> hypervisor
> kernel
> power
> fs
> module
> devices
> block
> dev
> bus
> class
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.stevens.edu/pipermail/cs631apue/attachments/20130921/6653cefc/attachment.html>


More information about the cs631apue mailing list