I'm trying to sort a 2d array of strings a simplified version looks like, ( I dont want to change the datatype of "nameArray" to "char *nameArray[4]" )
#include <sys/types.h>
#include <stdio.h>
int cstring_cmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcasecmp(*ia, *ib);
}
int Test()
{
char nameArray[4][10]={"test","alpha","Hyper","city"};
// int nElem = sizeof(nameArray)/sizeof(char *);
int index = 0;
//printf("nElem =%d\n", nElem);
for(index=0; index < 4; index++)
{
printf("-> %s\n", nameArray[index]);
}
qsort( &nameArray[0], 4, sizeof(nameArray[0]), cstring_cmp);
printf("After sort\n");
for(index=0; index < 4; index++)
{
printf("-> %s\n", nameArray[index]);
}
return 0 ;
}
( UPDATE: changed so that I'm directly using the value(4) instead of calculating nElem. My problem is getting the qsort to working. )
The arguments to the comparison function are just pointers, rather than pointers to pointers.
You also don't need to cast I believe, since the parameters are void *, you can just assign them to the local variables and the compiler takes care of them.
Try this:
int cstring_cmp(const void *a, const void *b)
{
const char *ia = a;
const char *ib = b;
return strcasecmp(ia, ib);
}
Or even get rid of the local variables if you don't need them (only need them if you're planning on adding more code to the comparison function):
int cstring_cmp(const void *a, const void *b)
{
return strcasecmp(a, b);
}
int cstring_cmp(const void *a, const void *b)
{
return strcmp(a, b);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.