关于数组两个元素地址相减的问题
2016-12-26 11:31
225 查看
#include<stdio.h> int a[5]={1,2,5,9,8}; main(){ int m,n,l,q; m = a-&a[3]; n = (char*)a-(char*)&a[3]; l = (int)a - (int)&a[3]; q = (int*)a - (int*)&a[3]; //&a[3] = a + 3; printf("Test the value of a is %d\n",a); printf("Test the value of &a[0] is %d \n",&a[0]); printf("Test the value of &a[1] is %d \n",&a[1]); printf("Test the value of &a[2] is %d \n",&a[2]); printf("Test the value of &a[3] is %d \n",&a[3]); printf("Test the value of m is %d \n",m); printf("Test the value of n is %d \n",n); printf("Test the value of l is %d \n",l); printf("Test the value of q is %d \n",q); }
运行结果:
![](https://images2015.cnblogs.com/blog/1031751/201612/1031751-20161226113214945-2138851440.png)
查看反汇编的代码,发现:
int nTmp = &a[4] - &a[0];
00416B87 lea eax,[ebp-28h]
00416B8A lea ecx,[arrayTmp]
00416B8D sub eax,ecx
00416B8F sar eax,2
00416B92 mov dword ptr [nTmp],eax
原来,执行完数组地址相减运算后,还会执行算数右移指令,右移位数视参数类型而定,如int型右移2位,short型右移1位。都知道右移1位相当于除以2操作,右移2位等同于除以4。
由此可见,两个数组元素地址相减,实际是获取两个元素数组元素的距离,而不是地址的距离。如果要计算地址距离,就直接强制类型转换:int nTmp = (char*)&a[4] - (char*)&a[0];
相关文章推荐
- 一个关于去除数组重复元素的问题(C语言实现)
- 关于字符串,字符数组 ,局部和全局地址分配问题
- 关于将数组地址赋给指针的问题
- 关于数组名的值,地址,表示以及强转等,有些绕的问题
- 一个关于去除数组重复元素的问题(C语言实现)
- 关于从list或者数组中随机抽取部分不重复元素的问题探究
- 关于数组地址问题
- [精彩] 关于LAN上有两个相同MAC地址的问题
- iOS小问题--使用NSPredicate比较两个数组中相同(不同)的元素
- 数组首元素地址和数组地址、int *ptr=(int *)(&a+1)问题的探讨
- 关于Java中交换数组中的两个元素的一个错误笔记
- 关于对数组名取地址的问题
- 关于数组地址的问题
- 关于求出两个整形数组不同元素,要求效率最高
- 关于数组首元素地址与数组首地址的区分
- 关于Leetcode里面求两个数组的第K值问题
- 关于swift for 循环 遍历数组删除元素的bug问题
- 关于去除JS数组中的重复元素问题
- 关于C语言数组之间元素操作的问题
- 关于成如何使用C语言处理数组元素c[-1]=0的问题