Dynamic memory allocation for matrices

I am coding in c++ on ubuntu. I am trying to dynamically create a matrix. I want to know what is wrong with this code. I am getting an error on {**matrix = new int *[row];} this line - invalid conversion from int** to int. I googled a lot, and everyone has used the same syntax. Please HELP, I've been stuck here for an entire day now!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int main()
{
	int **matrix;
	int i,j, count;
	int row;
	int col;
	
	cout << "\n Enter the number of rows and columns for the matrix.";
	cin >> row >> col ;
	
	 
	 **matrix = new int *[row];
	 for (count = 0; count < row; count++)
	 matrix[count] = new int [col];

		
	cout << "\nNow enter the element for the matrix."; 
	for (i=0; i < row; i++)
	{
		for (j=0; j < col; j++)
		{
		    cout << "\nRow " << (i+1) << " Col " << (j+1) << " :";
		    cin >> *(*(matrix + i) + j);
		}
	}
	
	for (int count = 0; count < row; count++)
	delete[] matrix[count];
	delete[] matrix;
	matrix = 0;
	return 0;
}
Last edited on
Line 12: usage of **matrix is erroneous because you've declared it already: line 3. That's all. So, the line 12 must be:

matrix = new int *[row];
Thanks a lot!
also consider using std::vector...
something like:
1
2
3
4
5
6
7
8
std::vector<std::vector<int>> matrix;
for (uint i = 0; i < row; ++i) {
  std::vector<int> tmp;
  for (uint j = 0; j < col; j++) {
    tmp.push_back(someValue);
  }
  matrix.push_back(std::move(tmp));
}
Last edited on
It is worth noting that std::vector<std::vector<int>> matrix is fine for the C++11 standard, but if he is using an older standard or not specifying -std=c++11, >> will generate errors.


1
2
3
std::vector<std::vector<int>> matrix;  // fine for C++11

std::vector<std::vector<int> > matrix;   // for pre-C++11 
Topic archived. No new replies allowed.