Is it possible to ask the user to input the size of a 2-dim array?

4
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by Agni

Of course, you may ask the user to input size or what else. The problem is what to do with the answer.
Better explain your problem, present source code snippets...

can you do something like this but with a 2-dim array?

``````int main()
{
int size;
int *pointer;

cout<<"Enter size\n";
cin>>size;
pointer=new int[size];

for(int i=0;i<size;i++)
{
pointer[i]=i;
}

for(int i=0;i<size;i++)
{
cout<<pointer[i]<<endl;
}

return 0;
}``````

You have to be a little more careful, but this is how you can do it.

``````int main()
{
int rows, cols;
int **pointer;

cout<<"Enter rows and columns for your 2-D array\n";
cin >> rows >> cols;

// allocate a row of pointers.
pointer = new int*[rows];

// for each row allocate the columns
for(int i = 0; i < rows; i++){
pointer[i] = new int[cols];
}

// add values to the 2-D array
for(int i=0;i < rows;i++){
for(int j = 0; j < cols; j++){
pointer[i][j]=(i + 1) * (j + 1);
}
}

// print out the values
for(int i=0;i<rows;i++){
for(int j = 0; j < cols; j++){
cout << pointer[i][j] << '\t';
}
cout << endl;
}

//free all the columns for each row
for(int i = 0; i < rows; i++){
delete pointer[i];
}
// free the rows
delete pointer;

return 0;
}``````

or you could do something like ...

``int* arr = new int[rows * cols];``

then go on adding elements to it ...

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.