2012-09-14 276 views
0

CASE1:二維數組初始化

int nrows=5; 
int ncols=10; 
int **rowptr; 
rowptr=new int*; 
for(int rows=0;rows<nrows;rows++) { 
    for(int cols=0;cols<ncols;cols++) { 
    *rowptr=new int; 
    } 
} 

CASE2:

int nrows=5; 
int ncols=10; 
int **rowptr; 
for(int rows=0;rows<nrows;rows++) { 
    rowptr=new int*; 
    for(int cols=0;cols<ncols;cols++) { 
    *rowptr=new int; 
    } 
} 

我能夠插入和使用兩種方式打印值。初始化有什麼區別?

+0

爲什麼沒有一個單一的答案提維度爲'N * M'的1D'std :: vector'?沒有愚蠢的內存泄漏。沒有指向嘗試表示數組的指針的指針。 – rubenvb

回答

2

有什麼區別?

#1只是分配內存足以容納一個整數指針而不是一個整數指針數組。
#2僅覆蓋前一次迭代的內存分配導致內存泄漏。

我能夠插入和使用這兩種方式

內存泄漏和未定義行爲打印值可能不會產生在你的程序立即observale錯誤的結果,但他們肯定是的好案例Murphy's Law

正確的方式做,這就是:

int nrows = 5; 
int ncols = 10; 

//Allocate enough memory for an array of integer pointers 
int **rowptr = new int*[nrows]; 

//loop through the array and create the second dimension 
for (int i = 0;i < nrows;i++) 
    rowptr[i] = new int[ncols]; 
1

你必須在這兩種情況下內存泄漏。

的正確方法來初始化這樣的「2D」陣列是

int** arr = new int*[nrows]; 
for (int i = 0; i < nrows; i++) 
    arr[i] = new int[ncols]; 

注意但是,它並不像由C/C++定義的2D陣列。它可能不會,也可能不會在記憶中連續。另外,用於訪問成員的彙編代碼也不同。

在你的情況下,通過索引訪問相當於*(*(arr+i)+j)

而在二維陣列的情況下,它*(arr + N_COLS*i + j)N_COLS是一個編譯時間常數。

如果你想有一個真正的二維數組,你應該做這樣的事情:

int (*arr)[N_COLS] = (int(*)[N_COLS])(new int[N_ROWS * N_COLS]) 
+0

內存泄漏如何,但? – user1583707

+0

您正在重新分配'rowptr'而不刪除它以前的內容。 – StoryTeller

0

你最好用一維數組來管理二維數組

int **x = new int*[nrows]; 
x[0] = new int[nrows*ncols]; 
for (int i = 1; i < nrows; i++) 
    x[i] = x[i-1] + ncols; 

for (int i = 0; i < nrows; i++) 
    for (int j = 0; j < ncols; j++) 
     x[i][j] = 0; 

delete [] x[0]; 
delete [] x;