二維數組與數組指標

來源:互聯網
上載者:User

標籤:pre   r++   ++   str   無法   位置   不同   數組   ptr   

int b[3][2], b是一個數組,b[0]是0行的首地址,b[1]是1行首地址,b[0]可以賦值給int*的指標,即b[i]是一維數組的首地址,b[i][j]訪問的i行第j個元素

int *s=b[0];   下面的代碼可以遍曆數組,輸出每個元素的首地址

for (int i = 0; i < 6; i++)                    
{
cout << s << " ";
cout << *s++ << endl;

}

for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
cout << &b[i][j] << endl;
}

二維數組名不是個2級指標,int **p=b,無法編譯,b的類型是int(*)[2] ,b是個指標,指向一個數組,b與b[0]不同,b[0]的類型是int* ,雖然b[0]也是0行的首地址

int (*ptr)[2] ; ptr=b;  下面的代碼可以遍曆數組元素

for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
cout << ptr[i][j] << endl;
}

for (int i = 0; i < 3; i++)   每次移動ptr,是移動整行,前面移動s,就是移動一個元素的位置,s是int*,ptr是int(*)[2]
cout << ptr++ << endl;    cout<<b[i]效果和cout<<ptr一樣

int(*t)[3][2],t是指標,指向3行2列的數組,b是指向2個元素的數組的指標,t=b不能通過編譯 

 

 1     int b[3][2] = { { 1, 2 }, { 2, 3 }, { 3, 4 } }; 2     int(*t)[3][2]; 3     t = &b; 4     int(*ptr)[2] = b; 5     for (int i = 0; i < 3; i++) 6         cout <<  ptr++ << endl; 7  8     int *s = b[0];// 9     cout << b[0] << " " << b[1]<<" " << b[2] << endl;10     for (int i = 0; i < 3; i++)11     {12         cout << t[i] << " ";13         cout << *t[i] << endl;14     }15     for (int i = 0; i < 6; i++)16     {17         cout << s << " ";18         cout << *s++ << endl;19         20     }21     for (int i = 0; i < 3; i++)22     {23         for (int j = 0; j < 2; j++)24             cout << ptr[i][j] << endl;25     }

 

二維數組與數組指標

聯繫我們

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