【发布时间】:2018-10-16 02:51:10
【问题描述】:
仅创建一个矩阵并将其打印出来后,我得到一个分段错误...我的矩阵的所有字符都被打印但在我打印的最后一行之后:
std::cout << endl;
我得到了分段错误。
我的代码:
标题:
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);
};
我的 CPP 代码:
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;
}
我的主要:
#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;
}
然后我得到:
* * * *
* * * *
* * * *
* * * *
Segmentation fault
但是如果我注释掉:"//cout 我没有任何分段错误。
问题出在哪里?它看起来太简单了,但仍然出现错误。 (有了额外的 cout
我看到here 在某些情况下,我正在访问我不应该到达的内存区域,但我知道并且我正在询问我的特定代码,这就是它的原因不是重复的。另外,here 有一个类似的问题,但很具体,与我的问题无关。
【问题讨论】:
-
如果您使用 C++ 编程,我建议您使用 STL 容器。你的代码会更干净,更不容易出错
-
@Jodocus 感谢您的意见,我尝试编辑更多问题,希望它符合标准
-
提供一些代码,让我们重现您的问题。在那之后,鉴于您在类构造函数中操作指针数组,我会说您的问题是运算符函数尝试访问取消引用的内存(因此出现段错误)。我强烈建议使用 std::vector 创建实现矩阵类
标签: c++ segmentation-fault ostream