![](/img/trans.png)
[英]Getting 'Segmentation fault' error when trying to load text file into a dynamically allocated 2d array
[英]Segmentation fault when passing values to dynamically allocated array
我正在完成一項需要模擬蘭頓螞蟻的任務。 我已經在Ant類的構造函數中為2D數組動態分配了內存。 指向此數組的指針是Ant類的成員。 另外,我為行和列定義了get函數,這些函數將這些值傳遞給我的數組。
螞蟻
#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::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()]的內存。
我不確定自己在做什么錯,任何幫助將不勝感激
假設board [getLastRow()] [getLastCol()]轉換為board [5] [5],您將超出緩沖區。 您的木板是0..4。
您正在通過超出范圍訪問數組元素來調用未定義的行為 。 您的setLastRow(5);
和setLastCol(5);
函數使您的getLastRow()
和getLastCol()
函數都返回5
的值,但是由於數組的索引為零 ,這意味着您正在訪問6th
元素。 因此:
board[getLastRow()][getLastCol()] = '#';
您實際上是在打電話:
board[5][5] = '#'; // undefined behavior because there are no 6 X 6 elements
而您的最大索引只能為4
:
board[4][4] = '#'; // OK as there are 5 X 5 elements
一種解決方案是讓您的函數分別返回lastRow - 1
和lastCol - 1
。
分段錯誤通常是指程序正在訪問未分配的地址。
董事會[getLastRow()] [getLastCol()]
您可能要檢查數組的開始索引和結束索引。
這產生==> board [getLastRow()-1] [getLastCol()-1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.