我在指针学习曲线上,可以真正使用一些方向/帮助。我希望有一个结构数组,每个结构都是一个跟踪各种事物的“单元格”。一切似乎工作正常,没有编译错误或任何东西,我正在使用数组生成一个地图。当我尝试在各个点访问阵列时,问题就出现了。有时我会得到内存访问违规,有时候我没有 - 这意味着我很幸运。我对C很新,所以任何帮助都会受到赞赏 - 或指向正确的方向。我真的很想知道为什么以及我出错的地方,我感觉这是我的指针和记忆 - 我正确地传递了什么?提前谢谢。
#define ysize 20
#define xsize 80
typedef struct cells {
int type;
bool visited;
bool passable;
int item;
} cells;
int getCell(int x, int y, struct cells **map)
{
return map[x + xsize * y]->type;
}
void setCell(int x, int y, int celltype, struct cells **map)
{
map[x + xsize * y]->type = celltype;
}
struct cells **makeMap()
{
struct cells **map = malloc(xsize * ysize * sizeof(struct cells *));
for (int i = 0; i != xsize * ysize; i++) {
map[i] = malloc(sizeof(struct cells ));
map[i]->type = 0;
map[i]->item = 0;
map[i]->passable = true;
map[i]->visited = false;
}
return map;
}
void main()
{
struct cells ** map = makeMap();
//getRand generates a random number between the min and max supplied.
int x = getRand(0, xsize);
int y = getRand(0, ysize);
if (getCell(x, y, map) == tileCorridor || getCell(x, y, map) == tileDirtFloor){
//map[x + xsize * y]->item = 3;
//printf("%d", getCell(x, y, map));
}
// this is where the code is failing.
//sometimes it works, others it generates a memory error
destroyMap(map);
}
答案 0 :(得分:0)
由于您正在将索引计算转换为一维,因此您不需要二维数组。这是您的代码的功能版本。我已经即兴创作getRand
并删除了destroyMap
这两个仍然缺失并添加了包含内容。
由于发布的代码主要有用,可能错误在其他地方。可能你的指数超出界限。
#include <malloc.h>
#include <stdlib.h>
#define ysize 20
#define xsize 80
typedef struct cells {
int type;
bool visited;
bool passable;
int item;
} cells;
int getCell(int x, int y, struct cells *map)
{
return map[x + xsize * y].type;
}
void setCell(int x, int y, int celltype, struct cells*map)
{
map[x + xsize * y].type = celltype;
}
struct cells *makeMap()
{
struct cells *map = (cells*) malloc(xsize * ysize * sizeof(struct cells));
for (int i = 0; i != xsize * ysize; i++) {
map[i].type = i;
map[i].item = 0;
map[i].passable = true;
map[i].visited = false;
}
return map;
}
int main()
{
struct cells * map = makeMap();
//getRand generates a random number between the min and max supplied.
for( int i = 0; i < 10000; ++i)
{
int x = rand() % xsize;
int y = rand() % ysize;
int tileCorridor = 21;
int tileDirtFloor = 143;
if (getCell(x, y, map) == tileCorridor || getCell(x, y, map) == tileDirtFloor){
//map[x + xsize * y]->item = 3;
printf("%d at [%d, %d] \n", getCell(x, y, map), x , y);
}
// this is where the code is failing.
//sometimes it works, others it generates a memory error
}
free(map);
}