標籤: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 }
二維數組與數組指標