I'm trying to sort a array of strings in C. But it can't run. It seems I misuse qsort. Program crash in calling qsort. How can I fix my code. Should i use const char* [] instead of char[][]? Why?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define N 40
#define MIN 4
#define MAX 10
int generateRandomNumber(int low, int high)/*generate random number between low and high inclusive*/
{
return rand() % (high + 1 - low) + low;
}
int comp(const void* a, const void* b)
{
const char* pa = *(const char**)a;
const char* pb = *(const char**)b;
return strcmp(pa, pb);
}
int main()
{
char words[N][MAX + 1];
int i, j;
int length;
srand(time(NULL));
for (i = 0; i < N; ++i)
{
length = generateRandomNumber(MIN, MAX);
for (j = 0; j < length; ++j)
{
words[i][j] = generateRandomNumber('a', 'z');
}
words[i][length] = '\0';
}
qsort(words, N, sizeof(char*), comp);
for (i = 0; i < N; ++i)
{
printf("%s\n", words[i]);
}
return 0;
}
sizeof(char*)-->sizeof(*words)2)const char* pa = *(const char**)a; const char* pb = *(const char**)b;-->const char* pa = (const char*)a; const char* pb = (const char*)b;