gpt4 book ai didi

c - 访问结构数组时发生内存冲突

转载 作者:行者123 更新时间:2023-11-30 17:03:11 27 4
gpt4 key购买 nike

我正处于指针学习曲线上,确实需要一些指导/帮助。我想要一个结构数组,每个结构都是一个跟踪各种事物的“单元”。一切似乎都工作正常,没有编译错误或任何东西,我正在使用数组来生成 map 。当我尝试在不同的点访问数组时,问题就出现了。有时我会遇到内存访问冲突,有时我不会 - 这意味着我很幸运。我对 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);
}

最佳答案

由于您正在对一维进行索引计算,因此不需要二维数组。这是您的代码的功能版本。我临时改进了 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);
}

Live on Coliru

关于c - 访问结构数组时发生内存冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36251963/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com