記憶體方面的測試題

來源:互聯網
上載者:User

int   main()
{
int   a[5]={1,2,3,4,5};
int   *ptr1=(int   *)(&a+1);
int   *ptr2=(int   *)((int   )a+1);
printf("%x,%x",ptr1[-1],*ptr2);
return   0;
}

C/C++ code
#include   <stdio.h>
int   main(void)
{
    int   a[5]={1,2,3,4,5};
    //假設a的地址為0x80000000,sizeof(int)=4
    //假設是little-endian,則0x80000000-0x80000013的資料為:
    // addr: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13
    // data: 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00
    int   *ptr1=(int   *)(&a+1); //ptr1 = 0x80000000+20=0x80000014
    int   *ptr2=(int   *)((int   )a+1); //ptr2 = 0x80000000+1 = 0x80000001
    //&ptr1[-1] = 0x80000014-4 = 0x80000010,so ptr1[-1] = *(int *)0x80000010 = 5
    //*ptr2 = *(int *)0x80000001 = 0x02000000
    printf("%x,%x",ptr1[-1],*ptr2);
    return   0;
}

 

http://topic.csdn.net/u/20071127/17/d521c586-bc0a-4c31-bcfe-5d90f0ed7c5e.html

 

所以在little-endian,32位機器上,輸出是5,2000000
big-endian,32位機器上,輸出是5,100
不知道結果對不對 ,但是分析不錯

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.