Thread: qsort

  1. #1
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926

    qsort

    could someone explain this function to me better. Especially the last argument thanx.

  2. #2
    Obsessed with C chrismiceli's Avatar
    Join Date
    Jan 2003
    Posts
    501
    http://developer.apple.com/documenta...l/qsort.3.html

    The last argument is a pointer to a function which returns certain number depending on how you want the list sorted. the function takes 2 arguments, two things from the list, the function will compare them then return the values accordingly, depending on how you write the function. Usually, people just return an strcmp() of the two values.
    Help populate a c/c++ help irc channel
    server: irc://irc.efnet.net
    channel: #c

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Usually, people just return an strcmp() of the two values.
    Maybe if they are strings.

    The compare functions takes in two const void pointers. As such you have to cast them to variables and then compare.

  4. #4
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    so the prototype would be something like this
    Code:
    int compare(const void *num1,const void *num2);
    then you would use it like so.
    Code:
    qsort((void*)buffer,strlen(buffer),sizeof buffer,(void *)compare);
    thank you

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >(void*)buffer
    No cast is needed to convert a pointer-to-T to a pointer-to-void.

    >(void *)compare
    A function pointer and a void pointer are not the same, this cast is dangerous and quite unnecessary since you can only do two things with a function, call it and take its address. If you aren't calling it then you must be taking its address and all is well as long as the type of the function pointers match.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. An interesting problem of qsort()
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 03-05-2008, 12:09 PM
  2. qsort() in Array of Pointer to String
    By vb.bajpai in forum C Programming
    Replies: 8
    Last Post: 06-16-2007, 04:18 PM
  3. trouble with qsort
    By qubit67 in forum C Programming
    Replies: 5
    Last Post: 04-29-2007, 10:23 PM
  4. Question About Using qsort
    By Zildjian in forum C Programming
    Replies: 3
    Last Post: 11-04-2003, 03:17 PM
  5. C++ link error with qsort
    By bvnorth in forum C++ Programming
    Replies: 7
    Last Post: 10-24-2003, 02:22 AM