使用键盘函数修改 C++ GLUT 中的二维数组指针

2D array pointer in C++ GLUT modified using keyboard function

我一直在尝试在用户输入键时修改二维数组网格。我的程序所做的就是创建一个二维网格,其中每个单元格都是 blocked/open。我在 main.cpp class 中分配二维数组,如下所示:

point** grid = new point*[size];
for (int i = 0; i < size; i++) grid[i] = new point[size];

然后,我通过名为 display() 的方法将其路由到我的 display.cpp。我创建了一个全局变量 point** g,用于存储我在 main.cpp 中分配的二维数组,然后,我在按下 space 时修改某些单元格的 blocked/open 值。

point** g;
void display(int argc, char** argv, float size, float gridSize, point** _g) {
    //Assign grid, sz and grid_Sz
    _g = g;
    sz = size;
    grid_Sz = gridSize;
    //Initialize the GLUT library and negotiate a session with the window system
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize(VWIDTH, VHEIGHT);
    glutCreateWindow("Pathfinding Creator");
    glutDisplayFunc(render_callback);
    glutKeyboardFunc(key_callback);
    glutReshapeFunc(resize);
}

//Key input callback
void key_callback(unsigned char key, int x, int y) {
//Start a point that the player is in at the top left corner of the grid (0,0)
    point position;
    position.x = 0;
    position.y = 0;

    //Constant ASCII codes
    const int ESC = 27;
    const int SPACE = 32;
    switch (key) {
    case ESC:
        exit(0);
        break;
    case SPACE:
        //Toggles the grid cell's 'blocked state' if true, put to false, false put to true...
        g[position.x][position.y].blocked = (g[position.x][position.y].blocked) ? false : true;
    }
}        

我遇到的问题是二维网格返回 main.cpp 的方法。我想要它回来,因为 main.cpp 处理将二维网格写入 .txt 文件的所有操作。

我现在尝试使 display() 不是 return 任何东西,并在我的 display.h 中将 _g 声明为外部点**,然后我在 main.cpp 中使用它。

这没有任何改变,我的程序仍然崩溃,并且出现访问冲突。当按下 space 或设置 _g[position.x][position.y].blocked 的赋值时,它会崩溃。 在 display.h:

extern point** _g;

在display.cpp中:

void display(int argc, char** argv, float size, float gridSize, point** grid) {
    //Assign grid, sz and grid_Sz
    sz = size;
    grid_Sz = gridSize;
    _g = grid;
    .....
}

最后,我只是将 main.cpp 中的 _g 分配给分配的网格:

point** grid = new point*[size];
for (int i = 0; i < size; i++) grid[i] = new point[size];
grid = _g;

我不确定是否有更好的方法来执行此操作,或者我以前的方法是否可以通过一些修补工作。任何帮助将不胜感激。

I think you misunderstand what your _g = g; line is doing. This will take the pointer value at g, and assign that value to the local variable _g. This will not copy the contents of what is pointed to. – 1201ProgramAlarm

非常感谢!我意识到 _g 实际上并没有复制 g 的内容,所以我将内存分配移到了 display.cpp 文件中,一切都从那里开始了。