gpt4 book ai didi

c++ - 无法为二维数组对象成员赋值

转载 作者:行者123 更新时间:2023-11-30 04:49:24 25 4
gpt4 key购买 nike

const int MAP_WIDTH = 100;
const int MAP_HEIGHT = 100;
const int RANDOM_POINTS = 10;
const int seeds = 3;

struct Point
{
int x;
int y;
int tileIndex;
};

Point* points = new Point[RANDOM_POINTS];
Point* mapPoints[MAP_WIDTH][MAP_HEIGHT];

Point* nearestPoint(int x, int y)
{
Point* ptr;
ptr = points;
Point* nearest_point;
int nearest_dis = 1000;
int distance;
for (int i = 0; i < RANDOM_POINTS; i++, ptr++)
{
int dx = ptr->x;
int dy = ptr->y;
distance = abs(dx - x) + abs(dy - y);
if (distance < nearest_dis)
{
nearest_point = ptr;
nearest_dis = distance;
}
}

return nearest_point;
}

int main(int argc,char* args[])
{
srand(seeds);
int min = 25;
int max = 75;
for (int i = 0; i < RANDOM_POINTS; i++)
{
points[i].x = rand() % (max - min + 1) + min;
points[i].y = rand() % (max - min + 1) + min;
points[i].tileIndex = rand() & 6;
}

std::ofstream mapFile;
//mapFile.open("res/mapFile.map",std::ios::app);

for (int px = 0; px < MAP_WIDTH; px++)
{
for (int py = 0 ; px < MAP_HEIGHT; py++)
{
mapPoints[px][py]->x = px;
mapPoints[px][py]->y = py;
mapPoints[px][py]->tileIndex = nearestPoint(mapPoints[px][py]->x, mapPoints[px][py]->y)->tileIndex;
std::cout << mapPoints[px][py]->x << mapPoints[px][py]->y << std::endl;
/*if(px<MAP_WIDTH-1)
mapFile << mapPoints[px][py]->tileIndex << ",";
else
mapFile << mapPoints[px][py]->tileIndex << "\n";*/
}
}
mapFile << std::endl;
mapFile.close();
//std::cout << nearestPoint(3, 3)->tileIndex << std::endl;
return 0;
}

points[RANDOM_POINTS] 存储随机生成的点。

mapPoints[MAP_WIDTH][MAP_HEIGHT] 是 map 大小。

这段代码的目的是将随机生成的图 block 类型索引输出到一个文本文件,所以我可以将它与 tileset.png 文件一起使用。

但我发现二维数组 mapPoints[MAP_WIDTH][MAP_HEIGHT] 是空的。无法为数据成员 x , y , index 赋值。 我不知道问题出在哪里。

最佳答案

Point* mapPoints[MAP_WIDTH][MAP_HEIGHT];
...
mapPoints[px][py]->x = px;

mapPoints 是一个指针数组。指针不指向任何地方。由于 mapPoints 是一个全局变量,它是用 nullptr 初始化的。 nullptr 是无效指针,取消引用它 mapPoints[px][py]->x 是未定义的行为,很可能导致类似于“段错误”或其他奇怪错误的事情。

如果你想存储一些东西,你需要有内存,而不是指针。

Point mapPoints[MAP_WIDTH][MAP_HEIGHT];
...
mapPoints[px][py].x = px;

同样在这一行中:

Point* points = new Point[RANDOM_POINTS];

您正在分配 RANDOM_POINTS 点。但是您永远不会删除它们。这会泄漏内存。只是做:

Point points[RANDOM_POINTS];

关于c++ - 无法为二维数组对象成员赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55413179/

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