关于数组两个元素地址相减的问题

#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);
}  

  

运行结果:

 

 

查看反汇编的代码,发现:
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];

posted @ 2016-12-26 11:31  琳麻雀  阅读(2137)  评论(0编辑  收藏  举报