使用键盘功能修改C GLUT中的2D数组指针

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

本文关键字:中的 2D 数组 指针 GLUT 键盘 功能 修改      更新时间:2023-10-16

当用户输入密钥时,我一直在尝试修改2D数组网格。我的程序所做的就是创建一个2D网格,每个单元格都被阻止/打开。我在Main.cpp类中分配2D数组,就像:

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

然后,我通过一种称为display()的方法将其路由到我的display.cpp。我创建一个全局变量点** g,以存储我分配给main.cpp中的2D数组,然后,我在按空格时修改某些单元格的阻止/打开值。

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;
    }
}        

我遇到的问题是2D网格回到main.cpp的一种方式。我想要它,因为main.cpp处理2D网格的所有写作。

我现在尝试使Display()不返回任何内容,并将_g声明为我的display.h中的extern Point.h,然后我在main.cpp中使用它。

这一切都没有改变,我的程序仍然崩溃,我会违反访问。当按下空间时,或者设置了_g [position.x] [position.y]的分配时,它会崩溃。在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;

我不确定是否有更好的方法可以做到这一点,或者我以前的方法是否可以使用一些修补。任何帮助将不胜感激。

我认为您误解了您的_g = g;线正在做。这将在G处将指针值分配给局部变量_G。这不会复制指向内容的内容。 - 1201 Programagalarm

谢谢!我意识到_g实际上并没有复制G的内容,因此我将内存分配移至display.cpp文件中,并且一切都从那里开始。