I am trying to write a program that allows a user to choose the size of a matrix and uses a function to allow the user to input values into an array based on the chosen size. My program compiles but then I get a segmentation fault core dumped error after entering the first value for the matrix.
//main program
#include "readMatrix.hpp"
#include <iostream>
int main()
{
int matrixSize; //variable to represent size of matrix
int **userMatrix; //pointer to pointer to create a dynamic 2D array
//Prompts user to enter desired matrix size
std::cout << "\nThis program will allow you to create a 2x2 or a 3x3 matrix.\n";
std::cout << "Please enter 2 to create a 2x2 matrix.\n";
std::cout << "Please enter 3 to create a 3x3 matrix.\n";
std::cin >> matrixSize;
//Validates input
while ((matrixSize < 2) || (matrixSize > 3))
{
std::cout << "Please enter 2 or 3.\n";
std::cin >> matrixSize;
}
//Creates matrix based on user choice of size
userMatrix = newint *[matrixSize]; //Creates the rows of the matrix
for (int mRow = 0; mRow < matrixSize; mRow++)
{
userMatrix[matrixSize] = newint [matrixSize]; //Creates the columns of the matrix
}
//Calls readMatrix to allow user to enter values into matrix
readMatrix(userMatrix, matrixSize);
//Displays matrix on screen
std::cout << "\nHere is the matrix you created.\n";
for (int row = 0; row < matrixSize; row++)
{
std::cout << std::endl; //Creates a new display line for each row
for (int col = 0; col < matrixSize; col++)
{
std::cout << userMatrix[row][col]; //Loops to display the value of each column in the row
}
}
//Frees dynamically allocated memory
delete [] userMatrix;
userMatrix = 0;
return 0;
}
//readMatrix header
#ifndef READMATRIX_HPP
#define READMATRIX_HPP
void readMatrix(int **, int);
#endif
//readMatrix implementation
#include "readMatrix.hpp"
#include <iostream>
/*************************************************
* *
* readMatrix *
* *
* This function prompts a user to fill in *
* values of a matrix and stores these values *
* in a dynamically allocated 2D array. *
* *
* Accepts: pointer to 2D array *
* integer (size of matrix square) *
* *
* Returns: nothing (void) *
* *
*************************************************/
void readMatrix(int **matrix, int size)
{
//Provides instructions for the user
std::cout << "\nYou may now enter values into the matrix.\n";
std::cout << "Values will be entered by row from left to right.\n";
std::cout << std::endl;
//Loops by row to allow user to enter values into the matrix
for (int r = 0; r < size; r++)
{
std::cout << "Please enter row " << r+1 << " values:\n";
for(int c = 0; c < size; c++)
{
std::cout << "Value " << (c+1) << ": ";
std::cin >> *(*(matrix + r) +c);
}
}
}