c语言用指针进行加减,【C语言学习笔记】指针的“加减”运算

例子1:

#include

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()

{

int arr[] = {10, 20, 30, 40, 50, 60};

int *ptr1 = arr;

int *ptr2 = arr + 5;

printf("Number of elements between two pointer are: %d.", (ptr2 - ptr1)); //5

printf("Number of bytes between two pointers are: %d", (char*)ptr2 - (char*) ptr1); //20

return 0;

}

解释:

Array name gives the address of first element in array. So when we do '*ptr1 = arr;', ptr1 starts holding the address of element 10. 'arr + 5' gives the address of 6th element as arithmetic is done using pointers. So 'ptr2-ptr1' gives 5. When we do '(char *)ptr2', ptr2 is type-casted to char pointer and size of character is one byte, pointer arithmetic happens considering character pointers. So we get 5*sizeof(int)/sizeof(char) as a difference of two pointers.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值