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

Recommended Answers

All 4 Replies

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 ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.