演示二維數組 int x[2][4] 的三種指針訪問方式:
int *x1ptr = &x[0][0],按一維偏移 *(x1ptr + i*4 + j)。int (*x2ptr)[4] = x,遍歷行 (*x2ptr)[j]。*(*(x+i)+j),標準數組指針語法。#include <iostream>
using std::cout; using std::endl; using std::cin;
int main() {
int x[2][4];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 4; ++j)
x[i][j] = i*10 + j;
int *x1ptr = &x[0][0];
int (*x2ptr)[4] = x;
// 方式1: 行指針遍歷
for (; x2ptr <= &x[1]; ++x2ptr) {
for (int j = 0; j < 4; ++j) cout << (*x2ptr)[j] << ' ';
cout << endl;
}
// 方式2: 雙重解引用
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 4; ++j) cout << *(*(x+i)+j) << ' ';
cout << endl;
}
// 方式3: 單指針偏移
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 4; ++j) cout << *(x1ptr + i*4 + j) << ' ';
cout << endl;
}
cin.get();
return 0;
}
0 1 2 3 10 11 12 13 0 1 2 3 10 11 12 13 0 1 2 3 10 11 12 13
理解二維數組在內存中連續佈局,行指針 int (*p)[cols] 步長為一行大小,單指針需手動計算偏移。靈活運用指針能簡化某些底層操作。