【发布时间】:2021-09-26 16:09:40
【问题描述】:
我写了一个函数,它计算一个正方形的所有顶点,给定它的位置和高度。由于不能在 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 = { ... };
}
【问题讨论】:
标签: c c99 designated-initializer