这是一个面试问题,我的朋友昨天被问到。问题是这样的:这个程序会崩溃与“访问冲突”错误或不?我看了一会儿,并认为不,它不会。但实际上在视觉工作室中尝试这一点证明了我的错误。我无法弄清楚这里发生了什么......或者更确切地说,我知道会发生什么,但不明白为什么。问题似乎是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