Dynamic two dimensional arrays
I have a problem declareing dynamic two dimensional arrays. In addition, I want to initialize all of the array's elements to 0, but I can't seem to do so.
This is basically my code:
Code:
cout << "Enter a number\n";
cin >> n;
int *arr = new int [n][n] = {{0},{0}};
Yet, the compiler generates an error. Whats wrong with the code?
Thank you
Here's a complete code for making dynamic 2d array
As you must be knowing that in arrays whether single or multidimensional, elements of arrays are stored in contigious memory location.So for building a dynamic two dimensional array i would suggest u to use a single dimensional dynamic array. Here is a simple program for ur better understanding
Code:
#include<iostream>
using namespace std;
int main()
{
int row,col;
int *arr;
cout<<"\nEnter number of rows";
cin>>row;
cout<<"\nEnter number of columns";
cin>>col;
//create array large enough to hold our 2D array
arr = new int[row*col]
//insert elements
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
cin>>arr[(i*col)+j];
cout<<endl<<endl;
//display elements
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
cout<<arr[(i*col)+j];
cout<<endl;
}
return 0;
}
note that to see how this single array works as a 2D array i would suggest you to take a paper and pencil and compute the values of arr[(i*col)+j] for different values of i and j. The program is write but still check for syntax errors.