gpt4 book ai didi

c++ - 二维数组分配问题

转载 作者:搜寻专家 更新时间:2023-10-31 00:48:02 24 4
gpt4 key购买 nike

这是我 friend 昨天被问到的面试问题。问题类似于:这个程序是否会因“访问冲突”错误而崩溃?我看了一会儿,心想不会,不会的。但实际上在 visual studio 中尝试这个证明我错了。我不知道这里发生了什么……或者更准确地说,我知道发生了什么,但不明白为什么。问题似乎是根本没有分配 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;
}

最佳答案

您正在按值传递双指针“matrix2”。因此,当 matrixAlloc 完成它的工作时,“matrix2”仍将是调用该函数之前的状态。为了获得要填充的更改,请考虑通过引用传递 matrix2:

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

不要忘记在必要时将 matrixAlloc 的实现更改为取消引用 matrix2。

编辑:下面的简单解决方案。更改此行:

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

为此:

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

关于c++ - 二维数组分配问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3125003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com