I want to create a non-rectangular matrix that can output something like this:
0 0 0 0 0 0
0 0 0
0 0 0 0
0 0 0 0 0 0
using 2-dimensional pointers.
I have a 1D pointer that points to an array which stores the size of each row : {6, 3, 4, 6, -1}.
-1 is a flag that will stop the while loop.
#include <iostream>
using namespace std;
template<class T>
T** allocate(int* sizes) {
T** twod; // 2-dimensional pointer
while (*sizes != -1) { // the loop will stop when *sizes hit -1
*twod = new T[*sizes];
twod++;
}
return twod;
}
int main() {
int array[] = {6,3, 4, 6, -1};
int* sizes = array; // 1-D pointer to the array which stores the size of each row
int** twod = allocate<int>(sizes);
for(int i = 0; i < 5; i++){
for(int j = 0; j < *(sizes+i); j++){
twod[i][j] = 0;
cout << twod[i][j] << " ";
}
cout << endl;
}
}
The program doesn't output anything. Can you guys help me point out the problem here? I think it might have to do with the while loop.
Thanks a lot!
(This is an assignment of mine regarding the use of pointers. I have to use pointers to output something above. I know using static arrays are much easier)