0

I am trying to figure out how to use qsort with an array of strings. My code looks like this.

char words[500][256];

int numOfWords; // this is calculated above

int sortWordList() {
    int length = sizeof(words) / sizeof(char *);
    qsort(words, length, sizeof(char*), compare);

}

int compare (const void * a, const void * b ) {
    const char *pa = *(const char**)a;
    const char *pb = *(const char**)b;

    return strcmp(pa,pb);
}

However, I get a "Access violation reading location 0x###.." everytime and I dont know whats wrong. Can anyone spot my problem?

EDIT: Thanks for the wonderful help. You guys are always the best.

1
  • 1
    Hint: a two-dimensional array of char is not the same as an array of pointers to char. Commented Apr 25, 2014 at 20:30

1 Answer 1

1

You are not casting your const void * to const char * properly, to do so, use instead:

const char *pa = (const char *)a;
const char *pb = (const char *)b;

Plus compare() should be above sortWordList() as you're using it in sortWordList().

Sign up to request clarification or add additional context in comments.

1 Comment

OK, so now the list gets sorted, but if I only have 90 elements in the list, the last 410 elements of empty space show up first. Is there a way to have my data show up first? (FIXED).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.