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

时间:2019-12-14 18:07:37

标签: c++ arrays printing dynamic-arrays

我一直在努力解决一个问题,我必须构建必须创建,填充和打印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;
}

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

1 个答案:

答案 0 :(得分:2)

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

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

您不会在代码中的任何地方删除该数组,因此会发生内存泄漏。请注意,每个new都应附带一个delete