I am making a class of matrix and trying to display by creating a new 2D matrix.When i compile and run this code,the program just exits and nothing appears on the screen.
I can’t understand the problem.Any help would be appreciated.thanks
#include <iostream>
using namespace std;
//making a class of matrix
class Matrix{
private:
int **array;
int row,col;
public:
void initialize(int r,int c); //function to initialize the array
//dynamically
Matrix(int r,int c); //this function initializes a matrix of r
//rows and c columns
~Matrix(); //delete the matrix by this
void display_matrix(); //display matrix
int get_rows(); //get rows of matrix
int get_columns(); //get columns of matrix
};
//function to initialize the matrix
void Matrix::initialize(int r,int c)
{
r=row;
c=col;
array=new int*[r]; //creating a 1D array dynamically
for (int i=0;i<r;i++)
{
array[i]=new int[c]; //making the array 2D by adding columns to it
}
for (int i=0;i<r;i++)
{
for (int j=0;j<c;j++)
{
array[i][j]=0; //setting all elements of array to null
}
}
}
//initializing NULL matrix
Matrix::Matrix()
{
initialize(0,0);
}
//setting row aand columns in matrix
Matrix::Matrix(int r,int c)
{
initialize(r,c); //function used to initialize the array
}
//deleting matrix
Matrix::~Matrix()
{
for (int i=0;i<row;i++)
{
delete[]array[i];
}
delete[]array;
}
int Matrix::get_rows()
{
return row; //return no. of rows
}
int Matrix::get_columns()
{
return col; //return columns
}
//display function
void Matrix::display_matrix()
{
int c=get_columns();
int r=get_rows();
for (int i=0;i<r;i++)
{
for (int j=0;j<c;j++)
{
cout<<array[i][j]<<" "; //double loop to display all the elements of
//array
}
cout<<endl;
}
}
int main()
{
Matrix *array2D=new Matrix(11,10); //making a new 2D matrix
array2D->display_matrix(); //displaying it
system("PAUSE");
return 0;
}
Your bug is in
initialize:You are setting the function variables ‘r’ and ‘c’ to whatever values the class variables ‘row’ and ‘col’ have. I’m pretty sure you meant to do the opposite.
Also are you sure this is the actual code you compile? Your class is missing a declaration for
Matrix()