又一次理解指標和數組

來源:互聯網
上載者:User

今天在網上看到一個面試題,題目描述如下:

#include <stdio.h>intmain(){    int a[5] = {1, 2, 3, 4, 5};     int *ptr = (int *)(&a + 1);     printf("%d %d\n", *(a + 1), *(ptr - 1));    return 0;}

請問輸出結果是什麼。

剛開始沒有看清楚

int *ptr = (int *)(&a + 1); 

這一句,理解為ptr是a[1]的地址,*(ptr-1)就是a[0]。

運行完發現這是錯誤的理解。隨後對程式做了debug

#include <stdio.h>intmain(){    int a[5] = {1, 2, 3, 4, 5};     int *ptr = (int *)(&a + 1);     printf("a0 = %p\n", &a[0]);    printf("a1 = %p\n", &a[1]);    printf("a2 = %p\n", &a[2]);    printf("a3 = %p\n", &a[3]);    printf("a4 = %p\n", &a[4]);    printf("-----------------\n");    printf("%p\n", &a + 1);     printf("%d %d\n", *(a + 1), *(ptr - 1));    return 0;}

運行結果如下:

a0 = 0xbff83220a1 = 0xbff83224a2 = 0xbff83228a3 = 0xbff8322ca4 = 0xbff83230-----------------0xbff832342 5

可以看出,每個元素佔用4個位元組,&a+1比a[0]的地址位移了14,這裡是16進位。因此轉換為10進位就是20.

因為每個元素佔用4個位元組,因此便宜了4*5=20.也就是位移了整個數組。

大概畫了個圖如下:

記錄一下,非常感謝乙醇同學的支援,希望對大家能有所協助,謝謝。

聯繫我們

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