代码
#include <stdio.h>
int main(void)
{
int urn[5] = {100,200,300,400,500};
int *ptr1, *ptr2, *ptr3;
ptr1 = urn; //第1个元素地址0x00007ffeefbff470
ptr2 = &urn[2]; //第3个元素地址0x00007ffeefbff478
printf("ptr1 = %p, *ptr1 = %d, &ptr1 = %p\n", ptr1, *ptr1, &ptr1); //ptr1表示第1个元素地址470 第1个元素值100 表示变量ptr1本身的地址460
ptr3 = ptr1 + 4; //批针与整数和相加意思是,整数与指针指向的类型的字节数相乘 再与初始地址相加(16进制)
printf("ptr1+4 = %p, *(ptr1+4) = %d\n", ptr1 + 4, *(ptr1 + 4)); //500的地址480 值500 (4*4=16位)
ptr1++; //自增指针,意思是指针移至下一个元素
printf("ptr1 = %p, *ptrl = %d, &ptr1 = %p\n", ptr1, *ptr1, &ptr1); //200的地址474 200 prt1指针变量自身的地址460
ptr2--; //先获取地址再减
printf("ptr2 = %p, *ptr2 = %d, &ptr2 = %p\n", ptr2, *ptr2, &ptr2); //474 200 ptr2变量自身的变量地址458
--ptr1;
++ptr2;
printf("ptr1 = %p, ptr2 = %p\n", ptr1, ptr2); //470 478
printf("ptr2 = %p, ptr1 = %p, ptr2 - ptr1 = %td\n", ptr2, ptr1, ptr2 - ptr1); //478 470 2(表示2个整形类型的字节)
printf("ptr3 = %p, ptr3 - 2 = %p\n", ptr3, ptr3 - 2); //480 478
return 0;
}
结果
ptr1 = 0x7ffeefbff470, *ptr1 = 100, &ptr1 = 0x7ffeefbff460
ptr1+4 = 0x7ffeefbff480, *(ptr1+4) = 500
ptr1 = 0x7ffeefbff474, *ptrl = 200, &ptr1 = 0x7ffeefbff460
ptr2 = 0x7ffeefbff474, *ptr2 = 200, &ptr2 = 0x7ffeefbff458
ptr1 = 0x7ffeefbff470, ptr2 = 0x7ffeefbff478
ptr2 = 0x7ffeefbff478, ptr1 = 0x7ffeefbff470, ptr2 - ptr1 = 2
ptr3 = 0x7ffeefbff480, ptr3 - 2 = 0x7ffeefbff478
Program ended with exit code: 0
Xcode10.2与macOS运行
。