I've been struggling with one issue, I have to build funtions that have to create and fill and print 2d dynamic array.
#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;
}
creating and filling works well and if I put some cout inside create_and_fill functions it also prints array. But if I try to print it using print function, there are some exceptions about forbidden actions. I simply don't understand why some functions can do this and other don't and how to fix it. Thanks!
The problem is you are passing the pointer by value. You allocate and fill the array then you leak, because the changes are not stored in the original pointer you passed to the function. If you want to modify the pointer itself you need to pass it by reference:
void create_and_fill(int **&T, int m, int n)
You don’t delete the array anywhere in your code, so you have memory leak. Please note that every new
should come with a delete
.