[英]Segmentation fault
#include <iostream>
using namespace std;
void initializeMap(int mapSizeX, int mapSizeY, int map[][10])
{
// Map details:
// 0 = # (wall)
// 1 = space (free space)
// 2 = x (player)
for(int x = 0; x < mapSizeX; x++)
{
map[x][0] = 0;
}
for(int y = 0; y < (mapSizeY - 2); y++)
{
map[0][y] = 0;
for(int x = 0; x < (mapSizeX - 2); x++)
{
map[x][y] = 1;
}
map[mapSizeX][y] = 0;
}
for(int x = 0; x < mapSizeX; x++)
{
map[x][mapSizeY - 1] = 0;
}
}
void paintMap(int mapSizeX, int mapSizeY, int map[][10])
{
for(int y = 0; y < mapSizeY; y++)
{
for(int x = 0; x < mapSizeX; x++)
{
switch(map[x][y])
{
case 0:
cout << "#";
break;
case 1:
cout << " ";
break;
case 2:
cout << "x";
break;
}
cout << map[x][y];
}
cout << endl;
}
}
int main()
{
int mapSizeX = 10;
int mapSizeY = 10;
int map[10][10];
initializeMap(mapSizeX, mapSizeY, map);
paintMap(mapSizeX, mapSizeY, map);
cout << endl << endl;
return 0;
}
我的代碼編譯得非常好,沒有錯誤,但是當我嘗試運行它時,它只是說“分段錯誤”。 我做了一些研究,但我不明白為什么我得到它,因為我根本不使用指針。 我該如何解決? 我使用 g++ 編譯它並通過在終端中鍵入 ./main 來運行它。
map[mapSizeX][y] = 0;
這是非法的。 索引的有效值從0
到mapSizeX - 1
。
該行應該是:
map[mapSizeX][y] = 0;
假設這是所需的 output?
#0#0#0#0#0#0#0#0#0#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0 1 1 1 1 1 1 1 1#0 #0#0#0#0#0#0#0#0#0#0
如果是這樣,您的initializeMap
function 中還有許多其他錯誤。 代替:
for(int y = 0; y < (mapSizeY - 2); y++)
和
for(int x = 0; x < (mapSizeX - 2); x++)
你應該使用
for(int y = 1; y < (mapSizeY - 1); y++)
和
for(int x = 1; x < (mapSizeX - 1); x++)
分別。
順便說一句,這是編寫initializeMap
的一種更簡潔的方法:
template<int mapSizeX, int mapSizeY>
void initializeMap(int (&map)[mapSizeX][mapSizeY])
{
for( int y = 0; y < mapSizeY; y++ ) {
for( int x = 0; x < mapSizeX; x++ ) {
if (x == 0 || x + 1 == mapSizeX || y == 0 || y == mapSizeY)
map[x][y] = 0;
else
map[x][y] = 1;
}
}
}
你可以用它來調用它
initializeMap(map);
無需傳遞大小,編譯器會自動計算出來。
我沒有深入了解這是否是您的代碼的唯一問題,但是
map[mapSizeX][y] = 0;
將寫在數組的邊界之上。
在initializeMap
的第二個for循環中 -
map[mapSizeX][y] = 0;
mapSizeX
為 10,矩陣中沒有10*y
元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.