My goal is dynamically allocate 2 dimensional array such that it prompts the user to input the size of the row and column of the matrix array they want to create. After dynamically allocating the size of the rows and columns, the user will input the values of whatever they wish. The following is my C++ code:
#include <iostream>
using namespace std;
int main()
{
int* x = NULL;
int* y = NULL;
int numbers, row, col;
cout << "Please input the size of your rows: " << endl;
std::cin >> row;
cout << "Please input the size of your columns: " << endl;
std::cin >> col;
x = new int[row];
y = new int[col];
cout << "Please input your array values: " << endl;
for (int i = 0; i<row; i++)
{
for (int j = 0; j<col; i++)
{
std::cin >> numbers;
x[i][j] = numbers;
}
}
cout << "The following is your matrix: " << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j<col; j++)
{
std::cout << "[" << i << "][" <<j << "] = " << x[i][j] << std::endl;
}
}
delete[] x;
delete[] y;
system("pause");
return 0;
}
Unfortunately, when I run this code on Visual Studios, it is giving me compile errors.
I solved it:
#include <iostream>
//#include <vector>
using namespace std;
int main() {
int row, col;
cout << "Please enter the rows size: " << endl;
cin >> row;
cout << "Please enter the column size: " << endl;
cin >> col;
cout << "Please enter the numbers you want to put into a 2D array (it should
look like a matrix graph)." << endl;
cout << "Press enter after each number you input: " << endl;
int** map = new int*[row];
for (int i = 0; i < row; ++i)
map[i] = new int[col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cin >> map[i][j];
}
}
cout << endl;
//Print
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << map[i][j] << " ";
}
cout << endl;
}
cout << endl;
// DON'T FORGET TO FREE
for (int i = 0; i < row; ++i) {
delete[] map[i];
}
delete[] map;
system("pause");
return 0;
}