So I started learning C++ last week and naturally, I want to become familiar with the whole pointer and object-oriented business and so on and so forth.
To do that, I'm writing a very simple program for some basic matrix calculations:
# include <iostream>
using std::cout;
using std::cin;
class Matrix {
int columns; // x
int rows; // y
double* matrix;
public:
Matrix (int*);
void printMatrix();
void free() {
delete[] matrix;
return;
};
};
Matrix::Matrix(int* dim){
rows = *dim;
columns = *(dim + 1);
matrix = new double [columns*rows];
}
void Matrix::printMatrix(){
int i, j;
for(i = 0; i < columns; i++){
for(j=0; j < rows; j++){
cout << matrix[columns*i + j] << " ";
}
cout << "\n";
}
return;
}
int* getMatrix ();
int main () {
Matrix matrix (getMatrix());
matrix.printMatrix();
matrix.free();
return 0;
}
int* getMatrix (){
int* dim = new int [2];
cout << "(m x n)-Matrix, m? ";
cin >> dim[0];
cout << "n? ";
cin >> dim[1];
return dim;
}
The problem (as I see it) occurs when I choose a (4,2) matrix. As I understand from various tutorials,
matrix = new double [columns*rows];
should allocate this much memory: columns*rows times sizeof(double). Also, every 'cell' should be initialized with a 0.
But, choosing a (4,2) matrix, I get the following output, of the function printMatrix():
0 0
0 0
0 6.6727e-319
0 0
Why is the (3,2) entry not initialized with 0?
Thanks!