Are you confused??
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
int cmpstringp(const void *p1, const void *p2);
char *nations[5]={"china","america","australia","france","german"};
int i;
for(i=0;i<5;i++)
printf("%s/n",nations[i]);
qsort(nations,5,sizeof(nations[0]),cmpstringp);
printf("/n/nafter sorting:/n/n");
for(i=0;i<5;i++)
printf("%s/n",nations[i]);
return 0;
}
/* int strcmp(const char *s1, const char *s2);
*/
int cmpstringp(const void *p1, const void *p2)
{
/* The actual arguments to this function are "pointers to
pointers to char", but strcmp() arguments are "pointers
to char", hence the following cast plus dereference */
return strcmp( *(char * const *)p1,*(char * const *)p2);
}
字符串在c中的定义是一个引用, 对存放 连续字符内存区的一个引用。比如, 可以这样定义:
一个指针数组就可以存储一组字符串, 如代码中的nations。nations[i]就类似上面定义的s, 但nations[i]在函数qsort里是作为一个数值型的地址,需要转换成char *型: (char*)p1, 再以地址的形式传到strcmp里: *(char *)p1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
int cmpstringp(const void *p1, const void *p2);
char *nations[5]={"china","america","australia","france","german"};
int i;
for(i=0;i<5;i++)
printf("%s/n",nations[i]);
qsort(nations,5,sizeof(nations[0]),cmpstringp);
printf("/n/nafter sorting:/n/n");
for(i=0;i<5;i++)
printf("%s/n",nations[i]);
return 0;
}
/* int strcmp(const char *s1, const char *s2);
*/
int cmpstringp(const void *p1, const void *p2)
{
/* The actual arguments to this function are "pointers to
pointers to char", but strcmp() arguments are "pointers
to char", hence the following cast plus dereference */
return strcmp( *(char * const *)p1,*(char * const *)p2);
}
字符串在c中的定义是一个引用, 对存放 连续字符内存区的一个引用。比如, 可以这样定义:
char *s = "hello";
s的实际值是一个地址值, 是int型。
一个指针数组就可以存储一组字符串, 如代码中的nations。nations[i]就类似上面定义的s, 但nations[i]在函数qsort里是作为一个数值型的地址,需要转换成char *型: (char*)p1, 再以地址的形式传到strcmp里: *(char *)p1