一、指针所占的字节
在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++ 错