【发布时间】:2018-01-17 17:16:50
【问题描述】:
我正在完成一项要求我模拟兰顿蚂蚁的任务。我在 Ant 类的构造函数中为二维数组动态分配了内存。指向该数组的指针是 Ant 类的成员。此外,我还为用于将这些值传递给数组的行和列定义了 get 函数。
Ant.hpp
#ifndef ANT_HPP
#define ANT_HPP
enum Direction {UP, RIGHT, DOWN, LEFT};
class Ant
{
private:
char** board;
char spaceColor;
Direction facing;
int rows, cols, steps, stepNumber;
int startRow, startCol, tempCol, tempRow;
int lastRow, lastCol;
int thisRow, thisCol;
public:
Ant();
Ant(int, int, int, int, int);
void print();
void makeMove();
};
Ant.cpp
Ant::Ant()
{
rows = 5;
cols = 5;
steps = 5;
startRow = 0;
startCol = 0;
stepNumber = 0;
facing = LEFT;
setThisRow(5);
setThisCol(5);
setLastRow(5);
setLastCol(5);
setSpaceColor(' ');
board = new char*[rows];
for(int i = 0; i < rows; ++i){
board[i] = new char[cols];
}
for(int i = 0; i < rows; ++i){
for(int i = 0; i < rows; ++i){
board[i][j] = ' ';
}
}
board[startRow][startCol] = '*';
}
char Ant::getSpaceColor()
{
return spaceColor;
}
void Ant::makeMove()
{
if(getSpaceColor() == ' '){
board[getLastRow()][getLastCol()] = '#';
}
}
int Ant::getLastRow()
{
return lastRow;
}
int Ant::getLastCol()
{
return lastCol;
}
main.cpp
#include "Ant.hpp"
#include <iostream>
using std::cout;
using std::endl;
int main()
{
Ant myAnt;
myAnt.print();
myAnt.makeMove();
return 0;
}
Gdb 报告了这行代码的分段错误:
board[getLastRow()][getLastCol()] = '#';
Gdb 能够打印 getLastRow() 和 getLastCol() 的准确值,但无法访问 board[getLastRow()][getLastCol()] 的内存。
我不知道我做错了什么,任何帮助将不胜感激
【问题讨论】:
-
我们也不确定,因为您没有包含
getLastRow等的代码 -
变量
board未初始化为指向正确分配的内存块。 -
我建议你远离 char** 并使用简单的 std::vector。按板寻址一个单元格[row_id*num_cols + col_id]