【发布时间】:2016-03-24 19:21:16
【问题描述】:
我知道 Seg Sault 是由访问不属于您的数据引起的,但我不明白为什么分配值和打印 9X9 二维数组的这一小段代码会返回 Seg Fault。请帮忙! 代码如下所示:
using namespace std;
#include <iostream>;
#include <string>;
string output = "|";
string topBoard[9][9];
int main() {
for (int i = 0; i < 9; i++) {
for (int ii = 0; ii < 9; ii++) {
topBoard[i][ii] = "empty";
}
}
for (int ii = 0; ii < 9; ii++) {
cout << "-----------------------------------------------------------------";
output = "|";
for (int i = 0; i < 9; i++) {
output = output + topBoard[ii][i] + "|";
}
cout << output;
}
return(0);
};
输出:
分段错误
进程以代码 139 退出
有人知道为什么会发生这种情况吗?
编辑:如果有人想查看它,我使用cloud9,它非常适合在任何地方处理您的东西。
进一步编辑: 这是您所有编辑的代码:
using namespace std;
#include <iostream>
#include <string>
const int Height = 9;
const int Width = 9;
string output = "|";
string topBoard[Height][Width];
int main() {
for (int i = 0; i < Height; i++) {
for (int ii = 0; ii < Width; ii++) {
topBoard[i][ii] = "empty";
}
}
for (int ii = 0; ii < Height; ii++) {
cout << "-----------------------------------------------------------------";
output = "|";
for (int i = 0; i < Width; i++) {
output = output + topBoard[ii][i] + "|";
}
cout << output;
}
return(0);
}
【问题讨论】:
-
9X9 2d array...for (int i = 0; i < 10; i++)循环 10 次。 -
记住这个模式:
T a[SIZE]; for (i=0;i<SIZE;++i) {...a[i]...}。说服自己没有SIZE-1或SIZE+1或<=。 -
另外,您不需要在包含语句的末尾附加分号。只需
#include <iostream>就可以正常工作,建议使用。 -
感谢您的帮助,我解决了问题,现在可以了!