Thread: Question About Using qsort

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    69

    Question About Using qsort

    Hello,

    I just have a simple question on the use of the qsort function. Say I have an array of strings such as:

    Code:
     char* str[] = {"Hello","Am","Where","Stuff"}
    How would I sort this with qsort? I'm just a little confused on what to pass to qsort as parameters. Also, how would it be done with an array whose elements aren't set at the beginning (i.e., the array is being filled up from input from stdin)? Thanks.

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    qsort()

    gg

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You'd probably get an answer from searching this board for 'qsort'
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Visionary Philosopher Sayeh's Avatar
    Join Date
    Aug 2002
    Posts
    212
    qsort() is used to sort 'blocks' of data. Usually, qsort() has a callback routine (your own code) that actually does the compare and returns whether one data 'block' is < or = or > the other data 'block'.

    As for what to pass, you pass the address of the data block. This can be an address to any nonmoving element in RAM. qsort() sorts pointers based on your evaluation of their contents.

    A 'block' of data could even be a structure:

    Code:
    typedef struct
       {
       int     myVal;
       long  otherData[16];
       long  moreData[32];
       }dataBlock;
    The callback might compare 'myVal' fields.

    Usually the comparison is really just a subtraction:

    Code:
       ...
       /* from inside the callback */
    
       return(mystruc1->myVal - myStruc2->myVal);
       }
    It is not the spoon that bends, it is you who bends around the spoon.

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. C++ link error with qsort
    By bvnorth in forum C++ Programming
    Replies: 7
    Last Post: 10-24-2003, 02:22 AM
  3. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  4. Replies: 7
    Last Post: 04-13-2003, 10:53 PM
  5. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM