當我們定義一個二維指標時,如果需要儲存相應的資料,就需要我們動態分配記憶體,這時,有一點是需 要注意的,分配記憶體的方法不同,記憶體的連續性也是不相同的,首先,博主先貼出測試代碼:
#include <cstdlib> #include <iostream> using namespace std; #define nWidth 3 #define nHeight 4 //記憶體是否連續分配問題 int main(int argc, char *argv[]) { int **p = NULL; p = (int**)malloc(nWidth*sizeof(int*)); if(p == NULL) return -1; cout<<"記憶體的不連續分配:"<<endl; for(int j = 0; j< nWidth; j++) { p[j] = (int*)malloc(nHeight*sizeof(int)); if(p[j] == NULL) return -1; } for(int i = 0; i < nWidth; i++) for(int j = 0; j < nHeight; j++) { printf("%p ",&p[i][j]); if(j == nHeight-1) cout<<endl; } cout<<endl; for(int j = 0; j < nWidth; j++) { free(p[j]); p[j] = NULL; } free(p); p = NULL; int **q = NULL; q = (int**)malloc(nWidth*sizeof(int*)); if(q == NULL) return -1; cout<<"記憶體的連續分配:"<<endl; q[0] = (int*)malloc(nWidth*nHeight*sizeof(int)); if(q[0] == NULL) { free(q); return -1; } for(int i = 1;i < nWidth; i++) q[i] = q[i-1] + nHeight; for(int i = 0; i < nWidth; i++) for(int j = 0; j < nHeight; j++) { printf("%p ",&q[i][j]); if(j == nHeight-1) cout<<endl; } cout<<endl; free(q[0]); q[0] = NULL; free(q); q = NULL; system("PAUSE"); return EXIT_SUCCESS; }