【C语言学习笔记】指针的“加减”运算

本文介绍了C语言中指针的加减运算规则。例如,指针加上一个值x实际上是增加了x乘以指针所指向类型大小的偏移量。同样,两个相同类型的指针可以相减得到它们之间的元素数量。通过示例,详细解析了指针运算在数组中的应用。
摘要由CSDN通过智能技术生成

例子1:

#include <stdio.h>
 
int main()
{
    float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};
    float *ptr1 = &arr[0]; // ptr1 is 925601136
    float *ptr2 = ptr1 + 3;// ptr2 is 925601148
 
    printf("%f ", *ptr2);//90.500000
    printf("%d", ptr2 – ptr1); //ptr2 - ptr1 is 3
 
   return 0;
}

解释:

When we add a value x to a pointer p, the value of the resultant expression isp + x*sizeof(*p) where sizeof(*p) means size of data type pointed by p. That is why ptr2 is incremented to point to arr[3] in the above code.Same rule applies for subtraction. Note that only integral values can be added or subtracted from a pointer. We can also subtract or compare two pointers of same type.


例子2:

int main()
{
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值