After only creating a matrix and printing it out I get a segmentation error... All chars of my matrix are printed but after the last line I print:
std::cout << endl;
and I get the segmentation error.
My code:
Header:
class Board{
private:
struct coord {
int x;
int y;
};
coord _coord;
char** board;
int size;
public:
Board(int v);
//~Board();
friend std::ostream& operator<<(std::ostream& os, Board const &b);
};
My CPP code:
Board::Board(int v)
{
size = v;
board = new char* [size];
for (int i=0; i<size; i++)
{
board[i] = new char[size];
for(int j = 0 ; j < size ; j++){
board[i][j] = '*';
}
}
}
ostream& operator<<(std::ostream& os, Board const &b)
{
for(int i = 0 ; i < b.size ; i++){
for(int j = 0 ; j < b.size ; j++){
cout << b.board[i][j] << " ";
}
cout << endl; // when (i == 3) the debug tells me after this I am thrown out
}
//cout << " " << endl;
}
My main:
#include "Board.h"
#include <iostream>
#include <vector>
//#include <map>
using namespace std;
int main() {
Board board1{4}; // Initializes a 4x4 board
cout << board1 << endl;
return 0;
}
Then I get:
* * * *
* * * *
* * * *
* * * *
Segmentation fault
but if I discomment: "//cout << " " << endl;" I don't have any more a segmentation error.
Where is the problem? it looks too simple but still, I am getting an error. (With the extra cout << " " << endl; line I am can continue and give in my assignment but I believe I should learn more and find out the problem)
I saw here that in whole in some situation that I am getting to an area in the memory that I am not supposed to get to, but that I know and I am asking on my specific code, that's why it is not a duplicate. Also, here there was a similar question but was specific and did not relate to my question.