![](/img/trans.png)
[英]How do I pass pointers to undeclared modifiable 1/2D arrays in c through a function and keep their values?
[英]How do I pass 2D struct arrays to different functions [SDL2/OpenGL Breakout project]
我正在使用 C 和 SDL2 开展一个突破项目。 我需要像这样创建砖墙。 主要问题是我对如何通过不同的函数传递结构数组缺乏了解,因为它在渲染时会导致分段错误。
首先,我创建了一个结构:
typedef struct bricks
{
double x;
double y;
double x0;
double y0;
double width;
double height;
double spacing;
double columns;
double rows;
char display; //1 if shown, 0 if it was hit (so its
hidden)
double power;
} bricks;
在 main 中,我使用它创建了一个 2D 数组:
int rows = 5, columns = 10, x, y;
bricks bricks[columns][rows];
for (int j = 0; j <= rows - 1; j++)
{
for (int i = 0; i <= columns - 1; i++)
{
initializeBricks(&bricks[i][j], 15, 10, columns, rows, 0, 0, i, j);
printf("%f\n", bricks[i][j]);
}
}
InitializeBricks function:
void initializeBricks(bricks *br, double h, double s, double col, double row, char dis, char p, int i, int j)
{
br->spacing = s;
br->columns = col;
int totalSpace = s * (col + 1);
br->width = (winWidth - totalSpace) / col;
br->x0 = (-winWidth/2) + s + (br->width/2);
br->y0 = (winHeight/2) - s - (h/2);
br->display = dis;
br->power = p;
br->x = br->x0 + (i * (s + br->width));
br->y = br->y0 - (j * (s + h));
printf("%f\n", br->x);
}
initializeBricks printf 验证计算是否在程序运行时正常工作,它会输出所有正确的 x 值。 但是主循环中的printf每次输出0.000000。
我也想可视化积木,但我的渲染方法不起作用。
主要:
render(&ball, &paddle, &bricks, winWidth, winHeight);
渲染功能:
void render(ball *b, paddle *p, bricks *br[][], int winWidth, int winHeight)
{
//draw the objects
for (int j = 0; j <= br[0][0].rows - 1; j++)
{
for (int i = 0; i <= br[0][0].columns - 1; i++)
{
drawBricks(&br[][], i, j);
}
}
}
void drawBricks(bricks *br, int i, int j)
{
glBegin(GL_QUADS);
glColor3f((double)j/3, (double)j/3 + 0.2, (double)j/6);
glVertex3d((br->x - (br->width/2)), (br->y + (br->height/2)), 0);
glVertex3d((br->x + (br->width/2)), (br->y + (br->height/2)), 0);
glVertex3d((br->x + (br->width/2)), (br->y - (br->height/2)), 0);
glVertex3d((br->x - (br->width/2)), (br->y - (br->height/2)), 0);
printf("hey");
glEnd();
glFlush();
}
我还应该提到我在之前的测试中生成了砖块,在这里,但我认为我需要使用结构,因为我想添加具有不同属性的碰撞和加电砖块。
简而言之,在这种情况下,我真的需要帮助理解结构、arrays 和指针,因为其他帖子对我没有太大帮助。
如果有人能指出我遇到的问题,我将不胜感激,欢呼。
bricks *br[][]
相当于bricks ***br
,我认为您没有以正确的方式访问它。
在渲染 function 中,当您编写br[0][0].rows
时它不正确,br 是指向bricks[][]
的指针,用于访问您想要的内容我认为您应该尝试以下操作: (*br)[0][0]
您想将bricks *
发送到drawBricks
function,因此您应该访问砖块参数,然后发送他的地址:
(*br)[j][i]
- 是砖的参数,并得到他的地址 - &((*br)[j][i])
对于您的代码,请尝试以下操作:
void render(ball *b, paddle *p, bricks *br[][], int winWidth, int winHeight)
{
//draw the objects
for (int j = 0; j <= (*br)[0][0].rows - 1; j++)
{
for (int i = 0; i <= (*br)[0][0].columns - 1; i++)
{
drawBricks(&((*br)[j][i]), i, j); // do you want to send the pointer of (*br)[j][i] to 'drawBricks' func ? tell me if i didn't get it right pls.
}
}
}
如果我没有正确理解您,请告诉我,希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.