打印 2D 动态数组 c++ 函数

Printing 2d dynamic array c++ function

本文关键字:c++ 函数 数组 动态 2D 打印      更新时间:2023-10-16

我一直在为一个问题而苦苦挣扎,我必须构建必须创建、填充和打印 2D 动态数组的功能。

#include <string>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <fstream>
using namespace std;
void create_and_fill(int **T, int m, int n)
{
T = new int *[m];
for (int i = 0; i < m; i++)
{
T[i] = new int[n];
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
T[i][j] = -100 + rand() % 201;
}
}
}
void print(int **T, int m, int n )
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cout << T[i][j] << "t";
}
cout << endl;
}
}
int main()
{
const int m = 5;
const int n = 6;
int **A = NULL;
create_and_fill(A, m, n);
print(A, m, n);
int **B = NULL;
create_and_fill(B, m, n);
return 0;
}

创建和填充效果很好,如果我在函数中放入一些 cout create_and_fill它也会打印数组。但是,如果我尝试使用打印功能打印它,则禁止的操作有一些例外。 我根本不明白为什么有些函数可以做到这一点而另一些函数不能以及如何解决它。谢谢!

问题是你正在按值传递指针。你分配并填充数组,然后泄漏,因为更改不会存储在你传递给函数的原始指针中。如果要修改指针本身,则需要通过引用传递它:

void create_and_fill(int **&T, int m, int n)

您不会在代码中的任何位置删除数组,因此会出现内存泄漏。请注意,每new均应附有delete