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);

// 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

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

commented: Your right -- thanks +20

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();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.