[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 280
  • Last Modified:

Qsort problems...

having problems with qsort. I use watcom c/c++

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int compare( const void *op1, const void *op2 )
  {
    const char **p1 = (const char **) op1;
    const char **p2 = (const char **) op2;
    return( strcmp( *p1, *p2 ) );
  }

void main()
  {
    char CharVect[3][10] = {{'\0'}};

    strcpy(CharVect[0],"last");
    strcpy(CharVect[1],"middle");
    strcpy(CharVect[2],"first");

    qsort( CharVect, 3,
          sizeof(char), compare );
    printf( "%s %s %s\n",
            CharVect[0], CharVect[1], CharVect[2] );
  }

does not sort...any suggestions ?
0
migue
Asked:
migue
  • 2
  • 2
1 Solution
 
imladrisCommented:
You don't need the compare function and the width is wrong. You should be able to do:

qsort(CharVect,3,10,strcmp);

0
 
imladrisCommented:
Note: the 10 is sizeof(CharVect[0]). Also qsort is expecting the elements to be presented in a block of memory (as CharVect is) and so simply passes pointers to the compare function, not pointers to pointers (it "knows" where the elements are given the information about the base address and the width).

0
 
AlexVirochovskyCommented:
1. wrong answer!
2. >>    qsort( CharVect, 3,   sizeof(char), compare ); <--error!
  must be:  qsort( CharVect, 3,   sizeof(char *), compare );

0
 
migueAuthor Commented:
answer is simply incorrect. I would like to cancel this issue, I wrote a quick sort myself.
Alex might be right.
0
 
AlexVirochovskyCommented:
My answer: my previous comment.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now