### 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!

 ``1234567891011121314151617181920212223242526272829303132`` ``````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:
 ``12345678`` ``````std::vector> matrix; for (uint i = 0; i < row; ++i) { std::vector 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.

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