Thread: Qsort and Dynamic Array

  1. #1
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681

    Qsort and Dynamic Array

    I'm 90% certain the problem is with how I'm using qsort().
    I verified that the compare function works by using bubble sort. I must be overlooking something but not sure what.

    Well here is the code, maybe one of you can point me to the right spot (or wrong spot depending on how you look at it )

    Note: Code attached due to length.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >qsort(sorted[0], (size_t)test.size, sizeof(sorted[0]), compare);

    Try:
    qsort(sorted, (size_t)test.size, sizeof(sorted[0]), compare);

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Thanks. It worked for an already sorted array however when I put in random numbers instead it didn't sort them.
    Last edited by Thantos; 12-12-2003 at 04:37 PM.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Your compare function is missing a level of indirection.
    Your array is an array of pointers, so the compare function gets pointers to pointers
    Code:
    int compare (const void * a, const void * b)
    {
      struct node * const *x = a;
      struct node * const *y = b;
      /*printf("%d %d\n", x->x, y->x);*/
      if ( (*x)->x > (*y)->x)
        return 1;
      else if ( (*x)->x < (*y)->x)
        return -1;
      else
        return 0;
    
    }
    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.

  5. #5
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Thanks both of you. That did it.

    Salem: Just want to repeat back what I think you are saying: Since my array is an array of pointers (hence the **) that means that my compare my also have double layered pointers?

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Try it with a typedef

    If you have an array of type T, then the compare function is called with two pointers of type T*
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can any1 plz make this assignment
    By jean in forum C Programming
    Replies: 17
    Last Post: 05-13-2009, 09:19 PM