指针数组-字符串数组

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中的定义是一个引用, 对存放 连续字符内存区的一个引用。比如, 可以这样定义:
char *s = "hello";
s的实际值是一个地址值, 是int型。

一个指针数组就可以存储一组字符串, 如代码中的nations。nations[i]就类似上面定义的s, 但nations[i]在函数qsort里是作为一个数值型的地址,需要转换成char *型: (char*)p1, 再以地址的形式传到strcmp里: *(char *)p1


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值