无法将值分配给2d数组对象成员

时间:2019-03-29 08:23:40

标签: c++

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]是地图大小。

此代码的目的是将随机生成的图块类型索引输出到文本文件,因此我可以将其与tileet.png文件一起使用。

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

1 个答案:

答案 0 :(得分:1)

chk1 %>% 
  rowwise() %>%
  mutate(ba_mat = sum(ba_mat_x, ba_mat_y, na.rm = T))

rowwise是一个指针数组。指针没有指向任何地方。由于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