Thread: qsort problem

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    70

    qsort problem

    I was trying to understand pointers to functions and came across qsort program

    can you guys tell me how the compare function "record_compare" works
    given the function
    Code:
    typedef struct {
    int key;
    } Record
    and

    Code:
    int record_compare (void cons *a, void const *a)
    { return ( ((Record *)a)->key - ((Record *)b)->key);
    }

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    The function takes in two void * constants. As you can not dereference a void point you have to cast it to the correct type.

    So (Record *)a casts a as a Record pointer. -> is the short hand to dereference a point to a structure or union and get a member.

    The function needs to return 0 if they are equal, greater then 0 if the first one is greater, or less then 0 if the second one is greater. Since you are really comparing two integer values by subtracting the second from the first you get those ranges.
    Last edited by Thantos; 05-24-2004 at 01:59 PM.

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    58
    very neatly put, thantos.
    even a fish would not have been in danger had it kept its mouth shut.

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    >Since you are really comparing two integer values by subtracting the second from the first you get those ranges.

    ...except that this technique will fail to produce correct results if there is integer overflow.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  2. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  3. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM
  4. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM
  5. Replies: 5
    Last Post: 11-07-2005, 11:34 PM