954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

qsort

Its pretty rare for me to post questions here but I came across this one about qsort I can't answer. If I try to sort an array of character strings such as char array[255][20] qsort works ok as expected. But if I declare the array like this qsort fails: char*array[255]

// this is ok
char array[255][20];
int NumStrings = 0;
// fill in the array is not shown here
qsort(array, NumStrings, sizeof(array[0]), compare);


or

// this fails
char* array[255]= {0};
int NumStrings = 0;
// fill in the array is not shown here
qsort(array, NumStrings, sizeof(array[0]), compare);
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

// fill in the array is not shown here
qsort(array, NumStrings, sizeof(array[0]), compare);

here,"sizeof(array[0])" is 20bytes;

// fill in the array is not shown here
qsort(array, NumStrings, sizeof(array[0]), compare);
but here,"sizeof(arry[0])" arry[0] is a pointer,so it's mean 4bytes

Beair.GQ
Newbie Poster
9 posts since Dec 2007
Reputation Points: 40
Solved Threads: 2
 

You have to change the signature of the compare function, to expect pointers to two character pointers, not pointers to two character arrays.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

Thanks, it works now :)

Below is for readers who may not realize what the solution was.

#include <stdio.h>

int compare(const void *a, const void *b)
{
    const char* a1 = *(const char**)a;
    const char* b1 = *(const char**)b;
    return strcmp(a1,b1);
}

int main()
{
    int c = 0;
    char* _array[] = {"now ","is  ","the ","time","for ","all ","good"}; 
    c = sizeof(_array)/sizeof(_array[0]);
    qsort(_array,c, sizeof(char*),compare);
    cout << "\n\nThe alphabetized words are:\n";
    for (int i = 0; i < c; i++)
    {
        cout << _array [i] << "\n";
    }
    cin.get();
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You