I want to initialize values of 2-D array to 0. But it seems not to work.
Can I initialize values of my **array in constructor to be 0. If yes the How.
My code is.
#include <iostream>
using namespace std;
int main(){
int row, col;
cin>>row;
cin>>col;
int **array=new int*[row];
for (int i=0; i<row; i++){
array[i]=new int[col];
}
for (int i=0; i<row;i++){
for (int j=0; j<col; j++){
array[i][j]={'0'};
cout<<array[i][j]<<" ";
}
cout<<endl;
}
}
Further can someone explain if I have to replace ith elem from the array with some other element, how would I deal with memory allocation.
You probably want
array[i][j]=0;. Why were you using thechartype'0'?However, there is an easier way:
array[i]=new int[col]();, just add()to value initialize each column.There also is a better way:
For your first comment, you would need to create a new array with the new size, copy over all the data, and the delete your old 2-d array.
For your second comment, here is an example:
PS: You can save yourself a lot of work by using
std::vector.