我写了一个函数,它计算一个正方形的所有顶点,给定它的位置和高度。由于不能在 C 中返回数组,因此我必须通过指针来完成。这是我最终编写的代码:
// Creates a rectangle for mapping a texture. Array must be 20 elements long.
void make_vertex_rect(float x, float y, float w, float h, float *vertex_positions) {
/* -1.0,+1.0 +1.0,+1.0
+----------------------+
| |
| |
| |
+----------------------+
-1.0,-1.0 +1.0,-1.0 */
float new_positions[20] = {
// We start at the top left and go in clockwise direction.
// x, y, z, u, v
x, y, 0.0f, 0.0f, 0.0f,
x + w, y, 0.0f, 1.0f, 0.0f,
x + w, y - h, 0.0f, 1.0f, 1.0f,
x, y - h, 0.0f, 0.0f, 1.0f
};
for (int i = 0; i < 20; ++i) { vertex_positions[i] = new_positions[i]; }
}
既然 C99 提供了指定的初始值设定项,我认为可能有一种方法可以在不编写 for 循环的情况下执行此操作,但无法弄清楚。有没有办法直接执行此操作,例如:
// Creates a rectangle for mapping a texture. Array must be 20 elements long.
void make_vertex_rect(float x, float y, float w, float h, float *vertex_positions) {
// Does not compile, but is there a way to get it to compile with a cast or something?
*vertex_positions = { ... };
}
最佳答案
Since one cannot return array's in C I have to do it through a pointer
这是真的。你不能直接返回一个数组,但是你可以返回一个包含数组的结构。这是一个解决方法:
struct rect {
float vertices[4][5];
};
struct rect make_vertex_rect(float x, float y, float w, float h) {
return (struct rect) {{
{x, y, 0.0f, 0.0f, 0.0f},
{x + w, y, 0.0f, 1.0f, 0.0f},
{x + w, y - h, 0.0f, 1.0f, 1.0f},
{x, y - h, 0.0f, 0.0f, 1.0f}
}};
}
显然,您可以将 rect
的定义更改为您认为最合适的任何定义,这主要只是为了说明这一点。只要数组大小不变(如此处所示),就没有问题。
关于C99 通过带大括号的指针初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68432975/