Thread: Using Library qsort() to Compare doubles

  1. #1
    Registered User
    Join Date
    Jun 2008
    Northern Va

    Using Library qsort() to Compare doubles

    I've got an array of doubles and wrote a simple comparison function, but when I run, my array remains unsorted. Your help is appreciated.
    double moment [1001];
    void *func = &dComp;
    int dComp(const void *a,const void *b) 
          if( &a < &b)
             return -1;
          else if( &a > &b) 
             return 1;
             return 0;  
    Also, I don't know much about function pointers, but considering gcc didn't spit out any errors, I think what I wrote was correct.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    You are comparing the address of the pointers, which is definitely absolute incorrect (&a will never be equal to &b, and &a > &b will be a constant for any given compiler - either true or false depending on the order of arguments fit on the stack in such a function).

    You will need to cast a and b to (const double *), then dereference those new pointers and return the comparison of that.

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    &a is the address of a, and &b is the address of b. So you're comparing addresses, not the values themselves.

    You'll also need to convince dComp that the things you're looking at are doubles and not "void", whatever the heck that is. So maybe something like
    double *left = a;
    And now you can compare *left and *right.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Library Wrapper
    By cusavior in forum C Programming
    Replies: 3
    Last Post: 03-25-2008, 10:27 AM
  2. An interesting problem of qsort()
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 03-05-2008, 12:09 PM
  3. Difficulty choosing graphics library
    By jdiperla in forum Game Programming
    Replies: 11
    Last Post: 02-27-2008, 06:35 PM
  4. Compare function for qsort
    By csisz3r in forum C Programming
    Replies: 8
    Last Post: 09-30-2005, 12:45 AM
  5. C++ link error with qsort
    By bvnorth in forum C++ Programming
    Replies: 7
    Last Post: 10-24-2003, 02:22 AM