2010-06-26 103 views
2

這是一個面試問題,我的朋友昨天被問到。問題是這樣的:這個程序會崩潰與「訪問衝突」錯誤或不?我看了一會兒,並認爲不,它不會。但實際上在視覺工作室中嘗試這一點證明了我的錯誤。我無法弄清楚這裏發生了什麼......或者更確切地說,我知道會發生什麼,但不明白爲什麼。問題似乎是matrix2數組根本沒有得到分配。下面二維數組分配問題

代碼:

#include <iostream> 
#include <ctime> 

using namespace std; 

int** matrixAlloc(const int rows, const int cols); 
void matrixAlloc(int** matrix, const int rows, const int cols); 
void matrixDealloc(int** m, const int rows); 
void matrixPrint(const int* const * const m, const int rows, const int cols); 

int main(int argc, char** argv) 
{ 
    srand((unsigned int)time(NULL)); 
    int** matrix1 = matrixAlloc(4, 5); 
    matrixPrint(matrix1, 4, 5); 
    matrixDealloc(matrix1, 4); 

    int ** matrix2 = NULL; 
    matrixAlloc(matrix2, 4, 5); 
    matrixDealloc(matrix2, 4); // <--- crash occurs here 
} 

int** matrixAlloc(const int rows, const int cols) 
{ 
    int **matrix = new int *[ rows ]; 
    for (int i = 0; i < rows; i++) 
    { 
     matrix[ i ] = new int[ cols ]; 
     for (int j = 0; j < cols; j++) 
     { 
      matrix[ i ][ j ] = (rand() * 12347) % 10; 
     } 
    } 

    return matrix; 
} 

void matrixAlloc(int** matrix, const int rows, const int cols) 
{ 
    matrix = new int *[ rows ]; 
    for (int i = 0; i < rows; i++) 
    { 
     matrix[ i ] = new int[ cols ]; 
     for (int j = 0; j < cols; j++) 
     { 
      matrix[ i ][ j ] = (rand() * 12347) % 10; 
     } 

    } 
} 

void matrixDealloc(int** matrix, const int rows) 
{  
    for (int i = 0; i < rows; i++) 
    { 
     delete [] matrix[ i ]; 
    } 
    delete [] matrix; 
} 

void matrixPrint(const int* const * const matrix, const int rows, const int cols) 
{ 
    for (int i = 0; i < rows; i++) 
    { 
     for (int j = 0; j < cols; j++) 
     { 
      cout << matrix[ i ][ j ] << " "; 
     } 
     cout << endl; 
    } 
    cout << endl; 
} 
+0

什麼可怕的混亂代碼。這是一個C++面試? – stinky472 2010-06-27 07:16:03

+0

我相信是的。有什麼可怕的呢? – PeterK 2010-06-27 09:17:27

回答

4

您正在通過值傳遞雙指針「matrix2」。因此,當matrixAlloc完成它的事情時,「matrix2」將仍然是函數調用之前的任何內容。爲了得到填充的變化,可以考慮通過引用傳遞矩陣2:

int** matrix2 = NULL; 
matrixAlloc(&matrix2, 4, 5); 
... 

不要忘記必要時matrixAlloc實施更改取消引用矩陣2。

編輯:下面的簡單解決方案。改變這一行:

void matrixAlloc(int** matrix, const int rows, const int cols) 

這樣:

void matrixAlloc(int**& matrix, const int rows, const int cols) 
+0

謝謝。就如此容易。不敢相信我沒看見! – PeterK 2010-06-26 18:35:40

1
matrixAlloc(matrix2, 4, 5); 

在這裏,您是按值傳遞矩陣2

void matrixAlloc(int** matrix, const int rows, const int cols) 
{ 
    matrix = new int *[ rows ]; 

在這裏,你正在分配給一個正式的參數。您傳入的實際參數不受此影響。您可能應該通過參考傳遞參數:

void matrixAlloc(int**& matrix, const int rows, const int cols) 
+0

Yeesh,複製我的答案很多? – 2010-06-26 18:34:56

+0

@wowus:大聲笑,*您*複製通過引用*從我*傳遞指針。或者,我們可能同時有相同的想法。像Newton和Leibnitz :) – fredoverflow 2010-06-26 18:59:01

+0

Dibs on牛頓:) – 2010-06-26 18:59:16