打印二维动态数组c++函数
Printing 2d dynamic array c++ function
我一直在努力解决一个问题,我必须构建必须创建、填充和打印二维动态数组的函数。
#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;
}
创建和填充效果很好,如果我在 create_and_fill 函数中放入一些 cout,它也会打印数组。但是,如果我尝试使用打印功能打印它,则有一些关于禁止操作的例外情况。
我只是不明白为什么有些功能可以做到这一点而其他功能却不能,以及如何解决它。谢谢!
问题是您按值传递指针。您分配并填充数组然后泄漏,因为更改未存储在您传递给函数的原始指针中。如果你想修改指针本身,你需要通过引用传递它:
void create_and_fill(int **&T, int m, int n)
你没有在代码中的任何地方删除数组,所以你有内存泄漏。请注意,每个 new
都应该带有一个 delete
。
我一直在努力解决一个问题,我必须构建必须创建、填充和打印二维动态数组的函数。
#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;
}
创建和填充效果很好,如果我在 create_and_fill 函数中放入一些 cout,它也会打印数组。但是,如果我尝试使用打印功能打印它,则有一些关于禁止操作的例外情况。 我只是不明白为什么有些功能可以做到这一点而其他功能却不能,以及如何解决它。谢谢!
问题是您按值传递指针。您分配并填充数组然后泄漏,因为更改未存储在您传递给函数的原始指针中。如果你想修改指针本身,你需要通过引用传递它:
void create_and_fill(int **&T, int m, int n)
你没有在代码中的任何地方删除数组,所以你有内存泄漏。请注意,每个 new
都应该带有一个 delete
。