I'm trying to use the new operator to allocate a 2d array. This is my function new2d.
int** new2d(int r, int c)
{
int **t = new int*[r];
for(int i = 0; i < r; i++)
t[i] = new int[c];
return t;
}
I'm pretty sure this is the correct way to do it. However, when I try to print the array like below
int **a = new2d(5, 9);
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 9; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
it gives this weird output with random 13,10,7...
0 0 0 0 13 0 0 0 0
0 0 0 0 10 0 0 0 0
0 0 0 0 7 0 0 0 0
0 0 0 0 4 0 0 0 0
0 0 0 0 0 0 0 0 0
Why does this happen?