關於數組兩個元素地址相減的問題

來源:互聯網
上載者:User

標籤:強制類型轉換   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];

關於數組兩個元素地址相減的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.