In: Computer Science
Cannot figure out why my c++ program keeps crashing, I am attempting to have the user decide the size of a 2d array then fill said array.
#include <iostream>
using namespace std;
typedef int* IntArrayPtr;
int main(void)
{
int column, row, i, j;
IntArrayPtr *arr_num = new IntArrayPtr[row];
cout << " " << endl
<< " This program creates a 2D array of dynamic memory, fills it with user entered numbers, " << endl
<< " Then prints the array to the screen. " << endl
<< " " << endl
<< " Enter the column dimensions of the array. " << endl
<< " " << endl;
cin >> column;
cout << " " << endl
<< " Enter the row dimensions of the array. " << endl
<< " " << endl;
cin >> row;
// This loop allocates dynamic memory for a 2D array of intigers.
// arr_num is now a 2dD array of dynamic memory and is of the size entered by the user.
for (i = 0; i < column; i++)
{
arr_num[i] = new int[column];
}
cout << " " << endl
<< " Enter " << column << " sets of " << row << " whole numbers. " << endl
<< " " << endl;
for (i = 0; i < column; i++)
{
for (j = 0; j < row; j++)
{
cin >> arr_num[i][j];
}
}
cout << " " << endl
<< " Now to display the 2D array of numbers entered. " << endl
<< " " << endl;
for (i = 0; i < column; i++)
{
for (j = 0; j < row; j++)
{
cout << arr_num[i][j] << " ";
cout << endl;
}
}
for (i = 0; i < column; i++)
{
delete[] arr_num[i];
}
delete[] arr_num;
return 0;
}
Its working properly I have tested it properly
#include <iostream>
using namespace std;
typedef int* IntArrayPtr;
int main(void)
{
int column, row, i, j;
IntArrayPtr *arr_num = new IntArrayPtr[row];
cout << " " << endl
<< " This program creates a 2D array of dynamic memory, fills it with user entered numbers, " << endl
<< " Then prints the array to the screen. " << endl
<< " " << endl
<< " Enter the column dimensions of the array. " << endl
<< " " << endl;
cin >> column;
cout << " " << endl
<< " Enter the row dimensions of the array. " << endl
<< " " << endl;
cin >> row;
// This loop allocates dynamic memory for a 2D array of intigers.
// arr_num is now a 2dD array of dynamic memory and is of the size entered by the user.
for (i = 0; i < column; i++)
{
arr_num[i] = new int[column];
}
cout << " " << endl
<< " Enter " << column << " sets of " << row << " whole numbers. " << endl
<< " " << endl;
for (i = 0; i < column; i++)
{
for (j = 0; j < row; j++)
{
cin >> arr_num[i][j];
}
}
cout << " " << endl
<< " Now to display the 2D array of numbers entered. " << endl
<< " " << endl;
for (i = 0; i < column; i++)
{
for (j = 0; j < row; j++)
{
cout << arr_num[i][j] << " ";
}
cout << endl;
}
for (i = 0; i < column; i++)
{
delete[] arr_num[i];
}
delete[] arr_num;
return 0;
}
Please comment below if you have any issues