【发布时间】:2018-01-19 23:04:48
【问题描述】:
我正在用 C 语言做一个学校项目,我需要做的是创建一个 2D 代理网格,其中一些是人类,另一些是僵尸。人类逃离僵尸,僵尸试图感染它们。
游戏是回合制的,每个回合的移动顺序都是随机的。为了做到这一点,我创建了一个包含所有代理的指针数组,这样我就可以在每次转弯之前对数组进行洗牌,然后通过循环遍历代理数组来获得随机代理移动顺序。
问题是,当我创建指针数组时出现分段错误,我不明白为什么。分段错误发生在这里:
agents_shuffle[c] = agent_new(type, playable, id, x, y);
感谢您的帮助!
这是程序主要部分的代码:
/* Array to save agent pointers for shuffle*/
AGENT **agents_shuffle = NULL;
AGENT_TYPE type = 0;
unsigned char playable = 0;
unsigned short id = 0;
int c = 0;
for (int x = 0; x < WORLD_X; x++) {
for (int y = 0; y < WORLD_Y; y++) {
if (agent_grid[x][y].type != None) {
type = agent_grid[x][y].type;
playable = agent_grid[x][y].playable;
id = agent_grid[x][y].id;
agents_shuffle[c] = agent_new(type, playable, id, x, y);
c++;
}
}
}
这是agent.c文件:
#include "agent.h"
AGENT *agent_new(AGENT_TYPE type, unsigned char playable,
short id, int x, int y) {
AGENT *a = (AGENT *) malloc(sizeof(AGENT));
a->type = type;
a->playable = playable;
a->id = id;
a->x = x;
a->y = y;
return a;
}
void agent_destroy(AGENT *a) {
free(a);
}
结构代理:
/**
* Structure defining agent properties.
* */
typedef struct {
AGENT_TYPE type; /**< Agent type. */
unsigned char playable; /**< Is agent playable? */
unsigned short id; /**< Agent ID. */
int x; /**< Agent position on x axis */
int y; /**< Agent position on y axis */
} AGENT;
这是定义的代理网格:
/** Horizontal world size. */
#define WORLD_X 10
/** Vertical world size. */
#define WORLD_Y 10
/* A by-dimensional array of agents, representing agents in a grid. */
AGENT agent_grid[WORLD_X][WORLD_Y];
/* Number of agents created so far. */
unsigned int nagents = 0;
/* Initialize random number generator. */
srand(time(NULL));
/* **************************************************************** */
/* Cycle through all cells in grid and randomly place agents in it. */
/* **************************************************************** */
for (int i = 0; i < WORLD_X; ++i) {
for (int j = 0; j < WORLD_Y; ++j) {
/* Possible agent in grid. By default we assume there is none. */
AGENT ag = {None, 0, 0, 0, 0};
/* Obtain a probability between 0 and 99. */
unsigned char probability = rand() % 100;
/* There is 10% probability of creating an agent. */
if (probability < 10) {
/* If we got here, an agent will be placed at (i,j). */
/* Randomly define agent type. */
ag.type = (rand() % 2 == 0) ? Human : Zombie;
/* Give 10% probablity of agent being playable by user. */
ag.playable = (rand() % 10 == 0);
/* Assign agent ID and then increment number of agents so
far. */
ag.id = nagents++;
/* Agent Coordinates */
ag.x = i;
ag.y = j;
}
/* Assign possible agent to grid at (i,j). */
agent_grid[i][j] = ag;
}
}
【问题讨论】:
-
agent_grid 在哪里定义?你会为此分配内存吗?
-
你需要为
agents_shuffle分配内存。我看不到您的代码中发生了什么。我看到的是您已将其分配给 NULL。 -
首先,您没有指定
agent_grid的位置以及如何为其分配内存。请记住,二维数组必须首先为外部数组分配内存,然后遍历数组并为每个单元分配内存以包含另一个数组。您也没有指定段错误发生的位置。
标签: c arrays pointers segmentation-fault