3

As far as I know, dynamically allocated 2d arrays should be allocated like this:

int **rows = new int*[7]; 
//for loop assigning all seven rows[i] a "new int[4]"

However, the following also works for me:

int (*ptr)[4] = new int[7][4];  //create dynamic 2d array
for(int i = 0; i < 7; ++i)      //initialize and test
{    
    for(int j = 0; j < 4; ++j)
    {
        ptr[i][j] = i + j;
        cout << ptr[i][j] << ' ';
    }
    cout << endl;
}
delete[] ptr;

 /* 
output: 
0 1 2 3 
1 2 3 4 
2 3 4 5 
3 4 5 6 
4 5 6 7 
5 6 7 8 
6 7 8 9 
*/

Why should I use the more complicated method I mentioned first, when I can create a dynamical 2d array with this one line:

int (*ptr)[4] = new int[7][4];

I appreciate any insights!

(I did not find a memory leak using valgrind.)

SQU901
  • 105
  • 1
  • 1
  • 7

2 Answers2

4

Why should I use the more complicated method I mentioned first, when I can create a dynamical 2d array with this one line:

You would need that when the number of columns are different in the rows. Say you have a 2D array that looks like:

1 2 3 4 5 6 7 8 9 10
1 2 3 4
9 8 8 5 6 4

For a case like this the second method won't work. You need to use:

p[0] = new int[10];
p[1] = new int[4];
p[2] = new int[6];
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

int (*rows)[4] requires that the 4 is a compile-time constant. You cannot use this method if the number of columns is not known until runtime.

However you should use neither of those methods. To write safe code, using raw pointers should be avoided. By using proper containers , memory management is done for you, meaning that your code is clear and less likely to contain mistakes.

// Neither rows nor columns known at compile-time
std::vector<std::vector<int>> x(7, std::vector<int>(4));

// columns known at compile-time
std::vector<std::array<int, 4>> x(7);

In both cases you can access the elements by x[5][2] and so on.

M.M
  • 138,810
  • 21
  • 208
  • 365