c++ - 将值传递给动态分配的数组时出现段错误

标签 c++ arrays pointers

我正在做一项作业,要求我模拟兰顿的 Ant 。我在 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;
}

主要.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()] 的内存。

我不确定我做错了什么,任何帮助将不胜感激

最佳答案

假设 board[getLastRow()][getLastCol()] 转换为 board[5][5],您超出了缓冲区。你的棋盘是 0..4。

关于c++ - 将值传递给动态分配的数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306609/

相关文章:

c 复制 ptr 的第一个字母

c++ - 分配给指针的值的存储持续时间

javascript - 为什么将 0 作为数组的第一个元素会阻止 "for"循环执行。 [JavaScript]

java - 如何构建二维数组金字塔

c++ - 为什么 clang 不允许派生类调用 protected 基函数?

c++ - 如何在 visual studio 中运行单个 google 测试?

java - 我正在从文本文件中读取数组,然后我应该大写字母,计算每个名称的出现次数,然后显示所有信息。

c - 如何在 C 中正确分配字符串数组中的指针?

c++ - 隐藏重载的虚函数

C++ 标准设置插入不是 "working"