指针中的算数运算

本文详细解析了指针在不同情况下的运算规则,包括指针加法、减法、指针间相减等,并对比了数组与指针的区别及联系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、指针所占的字节

       在X86 或者32位平台的指针4占字节。

       在X64 或者64位平台的指针8占字节。

二、指针加法运算:(指针加法运算需要调整,调整的权重是指针本身去掉一个*号,在求sizeof())

例1、

int main()
{
int *p = (int *)10000; 
printf("%d\n",p+1); //     10004                               (p为Int ,4个字节,10000+1(一个格子)*4)
printf("%d\n",p+4);// 10016                                    (p为Int ,4个字节,10000+4(四个格子)*4)
printf("%d\n",(char *)p+4); //10004                         (p为char,1个字节,10000+4(四个格子)*1)
printf("%d\n",(short *)p+4); //10008                        (p为short ,2个字节,10000+4(四个格子)*2)
printf("%d\n",(double *)p+4); //10032                      (p为double ,8个字节,10000+4(四个格子)*8)
printf("%d\n",(unsigned long long )p+1); //10001    (p为long long,8个字节,但是p不是指针,因此只+1)
printf("%d\n",(int ***)p+1); //10004                          (p为Int ,4个字节,本身去掉一个*后,它还是指针,指针占4字节,10000+1(四个格子)*4)


return 0;
}

 三、指针减法运算 :(指针减法运算需要调整,调整的权重是指针本身去掉一个*号,在求sizeof())

   指针减法需要调整,调整的权重是指针本身去掉一个*号,再求sizeof();
int main()
{
int *p = (int *)0x1010;      (%x是以16进制输出)
printf("%x\n",p-1);   //100c        (int 型 )
printf("%x\n",p-2);   // 1008
printf("%x\n",(short *)p-2);  // 100c   
printf("%x\n",(char *)p-2);   //100e
printf("%x\n",(double *)p-2); //1000
printf("%x\n",(float *)p-2);   //1008
printf("%x\n",(long long)p-2); //100e       (不是指针,直接 —2)
printf("%x\n",(double **)p-2)  //1008     (去掉一个* ,任然是指针,占4字节)下同
printf("%x\n",(char **)p-2);  //1008   


return 0;
}

四、指针减指针运算   (指针-指针,合法,需要调整,1、算出两个指针间隔的字节数,2、除以调整的权重,调整的权重是指针本身去掉一个*号,再求sizeof();)

       int main()
{
int arr[10] = {0};     
int *p = &arr[1];    //x+4
int *q = &arr[9];    // x+36
printf("%d\n",p-q);   // ((x+4)-(x+36))=-32   ,-32/4(int)=-8
printf("%d\n",q-p);   //  ((x+36)-(x+4))=32 ,32/4(int)=8
printf("%d\n",(short *)q-( short*)p);   //((x+36)-(x+4))=32 ,32/2(short)=16
printf("%d\n",(char **)q-(char **)p);  ///((x+36)-(x+4))=32 ,32/4(去掉一个*号,任然为指针4字节)=8
printf("%d\n",(double *)q-(double *)p);   //4
printf("%d\n",(long *)q-(long *)p);// 8
printf("%d\n",(char *)q-(char*)p);  //32
printf("%d\n",(long long)q-(long long)p)  // ((x+36)-(x+4))=32    (不是指针)


//printf("%d\n",(int *)q-(short *)p);   不同类型的指针不允许相减。


return 0;
}

     五、数组与指针的联系与区别

   *(arr+i)==arr[i]    //中括号自带解引用

    *(p+i)==p[i]      //i可为负值

不同点:

     sizeof(p)==4    指针为4个字节

     sizeof(arr)==40

    p++   对

    arr++   错


   













      

       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值