qsort Explanation

This is a discussion on qsort Explanation within the C Programming forums, part of the General Programming Boards category; Hi Everyone, I was wondering if someone could give me some help in understanding the following code and what certain ...

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    25

    qsort Explanation

    Hi Everyone,

    I was wondering if someone could give me some help in understanding the following code and what certain parts mean.

    Please speak in lamens terms. The final return statement is what I find most confusing....What does the *(char*)a and why is one in the bracket and one out?? Any help with understanding these lines of code would be greatly appreciated.

    int compare(const void *a, const void *b);

    int main(void)
    {
    .
    .
    .
    qsort((void *)ptr_array, NewMax, sizeof(ptr_array[0]), compare);
    .
    .
    .
    }
    int compare(const void *a, const void *b)
    {
    return (*(char*)a - *(char*)b);
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    A type in parenthesis is known as a "cast". This is used to tell the computer that you want to use one type of variable as another. In this case, the function takes void pointers.

    A pointer is a variable that points to another one. A void pointer can point to any data type.

    The values are type cast to tell the computer that what the void points to is actually a character pointer.

    The left most * is used to dereference a pointer. When you want to get what a pointer poitns at, you dereference it.

    In the end, it basicly takes one character and subtracts it from another.

    Quzah.
    Hope is the first step on the road to disappointment.

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. How to write my own qsort routine
    By tonbarius in forum C Programming
    Replies: 3
    Last Post: 05-14-2006, 01:34 PM
  3. malloced 2d array passed to qsort
    By jamie85 in forum C Programming
    Replies: 7
    Last Post: 11-25-2005, 01:55 PM
  4. C++ link error with qsort
    By bvnorth in forum C++ Programming
    Replies: 7
    Last Post: 10-24-2003, 03:22 AM
  5. Qsort
    By Tombear in forum C Programming
    Replies: 1
    Last Post: 10-28-2001, 09:06 AM

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