overloading problem

I'm trying to print out a matrix using a pointer
such that get the rows and cols with 0 numbers.
Compiled but there is a run time crash.
Note: I have to use a pointer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;
class Matrix {
private:
  int rows, cols;
	double* m;
public:
	Matrix(int rows, int cols) : rows(rows), cols(cols) {
		m = new double[rows*cols];
		// fill with zeros
		for(int i=0; i<rows*cols; i++){
            m[i] = 0;
		}
	}
	friend ostream& operator <<(ostream& s, Matrix m) {
		return s << m << '\n';
	}
	~Matrix() {
		delete [] m;
	}
int main() {
	Matrix m1(3,4);
	cout << m1; // should print all zeros!!!

}
Your << operator is recursive. It calls itself, but it never stops, so eventually it runs out of stack space and causes a segmentation fault.
How can I fix it?
Rewrite your operator<<() to actually output m's parts rather than call itself. You are defining how to print a Matrix in the function.
Topic archived. No new replies allowed.