這是一個面試問題,我的朋友昨天被問到。問題是這樣的:這個程序會崩潰與「訪問衝突」錯誤或不?我看了一會兒,並認爲不,它不會。但實際上在視覺工作室中嘗試這一點證明了我的錯誤。我無法弄清楚這裏發生了什麼......或者更確切地說,我知道會發生什麼,但不明白爲什麼。問題似乎是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;
}
什麼可怕的混亂代碼。這是一個C++面試? – stinky472 2010-06-27 07:16:03
我相信是的。有什麼可怕的呢? – PeterK 2010-06-27 09:17:27