數組名VS數組名取地址

來源:互聯網
上載者:User

實驗準備:

我們使用VC++6.0進行實驗,首先需要開啟VC++6.0的RTTI選項(預設關閉)

Project->settings->c/c++->category->c++language,將Enable Run-Time TypeInfomation(RTTI)選中


測試代碼:

 

#include <iostream>using namespace std;int main(){int array[3] = {2, 4, 6};typedef int (*ARRAY)[3];int *p = array;ARRAY q = &array;//int *q = &array; //編譯錯誤cout << "p = " << p << "\t\t" << typeid(p).name() << endl;cout << "q = " << q << "\t\t" << typeid(q).name() << endl;cout << "array = " << array << "\t\t" << typeid(array).name() << endl;cout << "&array = " << &array << "\t\t" << typeid(&array).name() << endl;cout << "*(p+1) = " << *(p + 1) << "\t\t" << typeid(*(p + 1)).name() << endl;cout << "*(q+1) = " << *(q + 1) << "\t\t" << typeid(*(q + 1)).name() << endl;cout << "*p+1 = " << *p + 1 << "\t\t" << typeid(*p + 1).name() << endl;cout << "*q+1 = " << *q + 1 << "\t\t" << typeid(*q + 1).name() << endl;cout << "*(*q+1) = " << *(*q + 1) << "\t\t" << typeid(*(*q + 1)).name() << endl;cout << "p+1 = " << p + 1 << "\t\t" << typeid(p + 1).name() << endl;cout << "q+1 = " << q + 1 << "\t\t" << typeid(q + 1).name() << endl;return 0;}

 

 

測試結果:

 

實驗結論:

1.      p和q的值相同,即array和&array是相同的,均指向相同的地址,但是兩個指標的類型不同,p(array)的類型是int *(整型指標),而q(&array)的類型是int (*)[3](數組指標),這也是語句“int *q = &array;”錯誤的原因

2.      因為p是int *類型的指標,故p+1=0018FF40,即每次+1,地址+4,指向數組中下一個資料;而q是int (*)[3]類型的指標,故q+1=0018FF48,即每次+1,地址+12(3*4),指向下一個數組

3.      *(p+1)==p[1]==array[1]==4,這很好理解;而按照相同的邏輯,*(q+1)==q[1]==(&array)[1],此時我們可以理解成“在記憶體中有一個更大的數組,其元素的類型為int [3],故q[1]就等價於指向這個大數組中的第二個元素”,根據2的解釋,我們知道“第二個元素”的地址為0018FF48

4.      *p+1很簡單,*p就是array數組中第一個元素,*p+1即將2加1,得3;而由恒等式*&x==x知,*q=*&array=array,即*q就是數組中第一個元素的地址,*q+1即將0018FF3C加1(指標+1等價地址+4),得0018FF40,此時*q+1的類型為int*,故對*q+1進行解引用(*)就是地址所指值,故*(*q+1)==array[1]==4

 

實驗圖解:

 

聯繫我們

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