I wanted to get familiar with 2D variable sized arrays in c++, so I wrote a little program, but it doesn’t work. Here is the code:
#include <iostream>
using namespace std;
int main(){
int a,i;
cin>>a; //the width of the array is variable
int **p2darray;
p2darray = new int*[2]; //the height is 2
for (i = 0; i < 2; i++){
p2darray[i] = new int[a];
}
i=0;
while(i!=a){
p2darray[0][i]=i; //filling some numbers in the array
p2darray[1][i]=2*i;
i++;
}
i=0;
while(i!=a){
cout<<p2darray[0][i]<<endl;
cout<<p2darray[1][i]<<endl;
i++;
}
return 0;
}
So why doesn’t it work?
The main problem is that when you say
p2darray[i][0], your indices are backwards because you set the second dimension to the size the user enters, but you’re incrementing the first dimension to that number instead. This would normally cause a segfault. It should bep2darray[0][i]in all four cases. You also didn’t setiback to 0 before entering the printing loop, so it’s skipping the entire printing process.For a running program that illustrates the said corrections, see here.