標籤:強制類型轉換 alt print 擷取 images sub 操作 類型轉換 log
#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];
關於數組兩個元素地址相減的問題