Using C-style arrays in C++ code will yield ghastly code. It's hard to read, hard to understand and what's the worst: hard to maintain. The proper solution here seems to be using std::vector
instead.
But in case you have a reason not to use std::vector
(i.e. it's some kind of school assignment), what you could do is to replace the original array with the newly-constructed one. So you have a pointer of type int (*)[2]
:
// create an array and initialize it:
int (*p)[2] = new (int [5][2]);
for(int i = 0; i < 5; i++)
for(int j = 0; j < 2; j++)
p[i][j]= (i+1) * (j+1);
now you can create a new array represented by a pointer of same type and reassign the original pointer (the fact that you're working with the continuous block of memory can be used here to copy elements):
int (*p2)[2] = new (int [6][2]);
memcpy(&p2[0][0], &p[0][0], sizeof(int) * 5 * 2);
delete[] p; // don't forget to clean up
p = p2;
but now there's some uninitialized memory that might cause undefined behavior so:
// initialize new row:
for(int j = 0; j < 2; j++)
p[5][j]= 6*(j+1);
and now you can print the values and destruct the newly-created array as well (which can be done using the pointer p2
but also using the pointer p
still):
for(int i = 0; i < 6; i++)
for(int j = 0; j < 2; j++)
std::cout << p[i][j] << ' ';
delete[] p;
which prints 1 2 2 4 3 6 4 8 5 10 6 12
:)
PS: If you have problems with memcpy
not being defined, try to #include <cstring>