使用键盘功能修改C GLUT中的2D数组指针
2D array pointer in C++ GLUT modified using keyboard function
当用户输入密钥时,我一直在尝试修改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文件中,并且一切都从那里开始。
相关文章:
- 如何在C++或OpenCV子矩阵中的2D子向量上使用OpenACC?
- 使用指针算法修改函数中的 2D 数组
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- QT3D 中的 2D 网格
- 如何在C++中的2d哈希表中查找值
- 英特尔并行工作室 2015 C++中的 2D 动态分配全局阵列
- 如何将列附加到现代C 中的2D向量
- 在 C++ 中实现 1D 数组中的 2D 数组坐标
- 从文本文件打印 sfml 中的 2D 数组
- C++中的 2D 迭代器访问
- 如何将整数数组的向量转换为C 中的2D数组
- 如何仅将数字值存储在给定输入文件中的2D数组中?(没有指针)
- 如何在C 中的2D动态数组中访问1个元素
- 使用键盘功能修改C GLUT中的2D数组指针
- 1D数组中的2D数组C
- MPI_Scatter在其他2D阵列中的2D数组
- 电话目录程序使用C 中的2D数组
- C 类中的2D动态数组
- 通过C 中的2D TIC-TAC-TOE阵列迭代的好方法
- 从C 中的2D集中删除元素