Using Library qsort() to Compare doubles

This is a discussion on Using Library qsort() to Compare doubles within the C Programming forums, part of the General Programming Boards category; Hello, I've got an array of doubles and wrote a simple comparison function, but when I run, my array remains ...

  1. #1
    Registered User
    Join Date
    Jun 2008
    Location
    Northern Va
    Posts
    18

    Using Library qsort() to Compare doubles

    Hello,
    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.
    Code:
    double moment [1001];
    ...
    void *func = &dComp;
    qsort(moment,1001,sizeof(double),func);
    ...
    
    int dComp(const void *a,const void *b) 
          {
          if( &a < &b)
             return -1;
          else if( &a > &b) 
             return 1;
          else 
             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
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    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.

    --
    Mats
    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
    Posts
    14,185
    &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
    Code:
    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, 11:09 AM
  3. Difficulty choosing graphics library
    By jdiperla in forum Game Programming
    Replies: 11
    Last Post: 02-27-2008, 05: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21