#include <iostream>
#include <cstring>
using namespace std;
const char* level1[23] =
{
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X X",
"X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X",
"X X K X D X X",
"X XXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXX X X",
"X X X X X XXXXX X X",
"X X XXXXX X XXXXXXXXXXXXXX XXXXXXXX XXXXXXXXXXX X X",
"X X X X D X X X X X XXXXX X",
"X X XXXX X X XXXXXXXXXX X X X XXXX X X",
"X X X X E X XXXXXXXXX XXXXXXXX X XXXXX X X",
"X XXXXXXXXXXXXXXXX D X XXK X X X X KX X",
"X X X X KX XXXXXX XXXXXX XXXXXXXX X X X XXXXXXDX",
"X X X X X X X XXX X X X X D X X",
"X X X X X X XXXXXXXXXXXXXXX XXXXXXXXXXXXXX X XXXXX X X",
"X X X X X X X X X KX X X X",
"X X X X X X X X XXXXXXXXXXX X XXXXXXXXXXX X XXXXX X",
"X X X X X X X X X X KX X X X X X",
"X X X X X X X X XX X X XXXXXXXXXXXXX X X",
"X X X X X X X X X XXXXXXXX X X X X X X",
"X X X X X X X X X X X X X X",
"X X XXXXXXXXXXXXX X XXXXXXXX X X X XXXXXXXXXXXXXXXXXX X",
"XS X X",
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
};
// Player structure
struct playerinfo
{
int x; // X position
int y; // Y position
int keys; // Number of keys the player has
};
// Current game info structure
struct gameinfo
{
char** board; // The maze array
int maxx; // Max size of the maze array X coordinate
int maxy; // Max size of the maze array X coordinate
int level; // The level of the maze
playerinfo player; // Link to player data struct
};
// Initializes the dynamic array that stores the maze
char** initboard(gameinfo game)
{
char** matrix = new char*[game.maxx];
for (int i=0; i<game.maxx; i++)
matrix[i] = new char[game.maxy];
return matrix;
}
void delboard(gameinfo game)
{
for (int i=0;i<game.maxx;i++)
delete [] game.board[i];
delete [] game.board;
}
int main()
{
gameinfo game;
game.maxx=65;
game.maxy=23;
game.board = initboard(game);
memcpy(game.board,level1,sizeof(level1));
delboard(game);
}
核心轉儲填充之後刪除動態二維數組時(核心轉儲)發生在的「delete [] game.board[i];
」的第一步...當使用memcpy()
線這隻發生。我想要做的是將c-string常量的內容複製到動態二維數組中。問題是,遊戲中會有多個可能不同大小的遊戲。我最初嘗試game.board[0] = "contents of line 0"
... game.board[23] = "contents of line 23"
,但這給了編譯器警告。奇怪的是,這完美地在Windows下使用MinGW,但我需要這個也可以在Linux上使用。中止使用的memcpy
你可能想問自己,當你調用它時,你實際上是'memcpy''嗎?你正在對剛分配的整個行緩衝區指針進行爆破,然後試圖「刪除」一堆從未實際分配過的指針。更糟的是,你這樣做*兩次*,每次都泄漏整個動態行緩衝區。並且這被標記爲** C ** ..爲什麼呢? – WhozCraig
而且地球上沒有機會「完美地運作」*任何地方*。你正在用靜態表中的'const char * *'序列替換一系列動態行緩衝區指針,然後在這些指針上調用'delete []'。編譯器後端無關緊要,你在做的是UB。 – WhozCraig
這真的讓我想起用C++編寫C代碼。通過使用一些C++容器來接受一些C++習慣用法,我保證你的生活會更容易。 – shuttle87