C/C++ 中「二維指針」int **p 並非真正的二維數組,而是「指向指針的指針」。動態分配時,分配策略直接決定內存是否物理連續,進而影響緩存局部性、memcpy 可行性、釋放方式等關鍵屬性。本文通過對比實驗深度剖析兩種主流分配模式。
int **p = malloc(rows * sizeof(int *));
for (int i = 0; i < rows; ++i)
p[i] = malloc(cols * sizeof(int));
malloc 獨立向堆請求內存,行與行之間地址不連續。realloc 擴容;內存碎片化時更易找到小塊。memcpy/memset;釋放需逐行 free 再 free(p)。
int **q = malloc(rows * sizeof(int *));
q[0] = malloc(rows * cols * sizeof(int)); // 一次性申請連續大塊
for (int i = 1; i < rows; ++i)
q[i] = q[i-1] + cols; // 指針運算定位行首
int (*arr)[cols] = malloc(rows * sizeof(*arr)) 的扁平化視圖。memcpy(q[0], src, rows*cols*sizeof(int)) 整體拷貝;單次 free(q[0]) + free(q) 釋放。#include <stdlib.h>
#include <stdio.h>
#define ROWS 3
#define COLS 4
void print_addrs(int **m, const char *tag) {
printf("%s:\n", tag);
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLS; ++j)
printf("%p ", (void*)&m[i][j]);
puts("");
}
puts("");
}
int main() {
// 策略一:不連續
int **p = malloc(ROWS * sizeof(int *));
for (int i = 0; i < ROWS; ++i) p[i] = malloc(COLS * sizeof(int));
print_addrs(p, "非連續分配");
for (int i = 0; i < ROWS; ++i) free(p[i]);
free(p);
// 策略二:連續
int **q = malloc(ROWS * sizeof(int *));
q[0] = malloc(ROWS * COLS * sizeof(int));
for (int i = 1; i < ROWS; ++i) q[i] = q[i-1] + COLS;
print_addrs(q, "連續分配");
free(q[0]);
free(q);
return 0;
}
非連續分配:
0x55a0 0x55a4 0x55a8 0x55ac
0x55c0 0x55c4 0x55c8 0x55cc ← 行首地址跳躍
0x55e0 0x55e4 0x55e8 0x55ec
連續分配:
0x5600 0x5604 0x5608 0x560c
0x5610 0x5614 0x5618 0x561c ← 行首地址連續遞增 16 字節
0x5620 0x5624 0x5628 0x562c
| 策略 | 釋放代碼 | 注意點 |
|---|---|---|
| 逐行獨立 | for(i) free(p[i]); free(p); | 順序無關,但必須逐行 |
| 連續大塊 | free(q[0]); free(q); | 僅 q[0] 指向數據塊,q[1..] 為衍生指針不可 free |
// C++11 連續二維數組,RAII 自動管理
std::vector> mat(rows, std::vector(cols)); // 不連續
std::vector flat(rows * cols); // 連續扁平
auto at = [&](int r, int c) -> int& { return flat[r*cols + c]; };
std::vector 保證連續、異常安全、零手動 free,應為首選。
std::vector 扁平化。int arr[MAX_R][MAX_C] 避免堆碎片。理解「指針數組」與「真二維數組」在內存佈局上的本質差異,是寫出高性能、無洩漏 C/C++ 代碼的基礎。默認優先選擇連續分配(或 std::vector),僅在需要鋸齒結構時退回到逐行分配,並嚴格遵循對應的釋放模式。