The problem in your code is that sizeof(char*) is the size of a pointer (usually 4 or 8 depending on your platform), but you need to provide the size of one element which is 10.
In the following code the all sizes (maximum string length and number of strings) are calculated with the the sizeof operator.
Explanation:
int maxstrlength = sizeof(d[0]); : this is the size of one string element (10 in your case)
int nbofstrings = sizeof(d) / sizeof(d[0]); : this is the number of elements (or strings). IOW the total size of d (50 here) divided by the size of one element (10) which is 5.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int my_compare(const void* a, const void* b)
{
const char* str1 = (const char*)a;
const char* str2 = (const char*)b;
return strcmp(str1, str2);
}
int main()
{
char d[5][10];
strcpy(d[0], "123456789");
strcpy(d[1], "1");
strcpy(d[2], "7");
strcpy(d[3], "200000");
strcpy(d[4], "300400000");
int maxstrlength = sizeof(d[0]);
int nbofstrings = sizeof(d) / sizeof(d[0]);
for (int i = 0; i < nbofstrings; i++) // display strings before sorting
printf("d[%d] = \"%s\"\n", i, d[i]);
printf("\n");
qsort(d, nbofstrings, maxstrlength, my_compare);
for (int i = 0; i < nbofstrings; i++) // display strings after sorting
printf("d[%d] = \"%s\"\n", i, d[i]);
}
BTW: in my_compare the pointers should be casted to const char* rather than char*, but this is nitpicking.
sizeof d[0](which is10), notsizeof(char*)dis not achar*but achar[10]. This means that the size-parameter you pass toqsort()should be10or better*dchar *d[5];and you then didd[0] = "123456789"; ...qsort( d, 5, 10, my_compare );fixes it. Thanks.