二維數組名和指針
#include <iostream> using namespace std; #define M 2 #define N 3 int main() { int a[M][N] = {1,2,3,4,5,4}; cout<<&(a[0])<<endl; //00DCFA64 cout<<&(a[0])+1<<endl; //00DCFA70,offest:12 cout<<a<<endl; //00DCFA64,a=&(a[0]), cout<<a+1<<endl; //00DCFA64 cout<<&(a[0][0])<<endl; //00DCFA64 cout<<&(a[0][0])+1<<endl; //00DCFA68,offest:4 int* ptr = (int*)(a); //ptr=&(a[0][0]) cout<<ptr<<endl; //00DCFA64 //for(int i = 0; i < sizeof(a)/sizeof(int); i++) //{ // if((*ptr++) == 4) // { // cout << "i=" << i/N << ", j=" << i%N << endl; // } //} return 0; }
&a[0]、&a[0][0]的值是相等的,但意義不同(對編譯器來說),因為a[0] 保存的是一個指向一個具有3個元素的整型數組,而&a[0]則是獲取這個數組的地址, 同樣對于a[0][0]來說,a[0][0]是a[0]數組中的第一個數據,也就是一個整數,&a[0][0]則是這個整數的地址,因此在指針操作上結果不同。
理解上,變量a是一個具有2個元素的數組,這2個元素是一個具有3個元素的整型數組。
int a[M][N] = {1,2,3,4,5,4}; 寫成 int a[M][N] = {{1,2,3},{4,5,4}}; 更容易理解。
數組名a=&a[0]
另外,二維數組在內存中占據連續的空間,在內存中從上到下存儲各行元素,在同一行中按照從左到右的順序存儲。因此,可以考慮定義一個指針 int* ptr = (int*)(a); ,更方便地訪問二維數組的元素。
#include <iostream> using namespace std; // 二維數組matrix中,每一行都從左到右遞增排序, // 每一列都從上到下遞增排序 //判斷一個整數是否在該二維數組中 bool Find(int* matrix, int rows, int columns, int number) { bool found = false; if(matrix != NULL && rows > 0 && columns > 0) { int row = 0; int column = columns - 1; while(row < rows && column >=0) { if(matrix[row * columns + column] == number) { found = true; break; } else if(matrix[row * columns + column] > number) -- column; else ++ row; } } return found; }
上例中,在給函數Find()傳遞參數時,要用(int*)matrix,而不能直接使用二維數組名matrix。
注意數組內元素的索引方式。
浙公網安備 33010602011771號