【发布时间】:2021-12-30 22:14:26
【问题描述】:
我必须为学校编写一个战舰游戏,所以我试图生成玩家将要放置他们的船的地图,我有一个段错误,但我不明白为什么。
这是我的代码:
主要:
int main(int ac, char **av)
{
map_data map_data;
print_map(map_gen(map_data));
return(0);
}
结构:
typedef struct map_data {
int lines;
int letters;
int width;
int height;
}map_data;
地图生成:
char **map_gen(map_data map_data)
{
map_data.lines = 0;
map_data.width = 18;
map_data.height = 10;
map_data.letters = 65;
char **map = malloc(sizeof((char)18 * 10));
for (int s = 0; s <= map_data.height ; s++) {
for (int c = 0; c <= map_data.width; c++) {
map_fill(map, map_data, s, c);
}
}
return (map);
}
char **map 的填充:
void char_fill(char **map, char ch, int s, int c)
{
map[s][c] = ch;
}
void map_fill(char **map, map_data map_data, int s, int c)
{
if (c == 1)
char_fill(map, '|', s, c);
if (s == 1)
char_fill(map, '-', s, c);
if (c == map_data.width)
char_fill(map, '\n', s, c);
map_fill2(map, map_data, s, c);
}
int map_fill2(char **map, map_data map_data, int s, int c)
{
if (s == 0 && c == 0)
char_fill(map, ' ', s, c);
if (s == 1 && c == 1)
char_fill(map, '+', s, c);
if (c > 1 && c % 2 == 0)
char_fill(map, '.', s, c);
if (s > 1 && c % 2 == 1)
char_fill(map, ' ', s, c);
if (s == 10 && c == 18)
char_fill(map, '\0', s, c);
if (s > 1 && c == 0) {
char_fill(map, my_int_to_char(map_data.lines), 0, 0);
map_data.lines = map_data.lines + 1;
}
if (!map[s][c]) {
my_putstr("error filling the map, please try again.");
return (EXIT_FAILURE);
}
}
打印:
void print_map(char **map)
{
int h = 0;
int w = 0;
while (map[h][w] != '\0') {
while (map[h][w] != '\n') {
my_putchar(map[h][w]);
w = w + 1;
}
h = h + 1;
}
}
我做错了吗? 关于如何改进我的代码的任何提示?
谢谢
【问题讨论】: