c - C99 通过带大括号的指针初始化数组
问题描述
我写了一个函数,它计算一个正方形的所有顶点,给定它的位置和高度。由于无法在 CI 中返回数组,因此必须通过指针来完成。这是我最终编写的代码:
// 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 = { ... };
}
解决方案
由于无法在 CI 中返回数组,因此必须通过指针来完成
这是真的。您不能直接返回数组,但可以返回包含数组的结构。这是一个解决方法:
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
您认为最合适的任何内容,这主要是为了说明这一点。只要数组大小是恒定的(因为它们在这里),就没有问题。
推荐阅读
- git - 如何仅在变更集中暂存行删除?
- java - 如何使用 Powermock、easymock、mockito 对 DriverManager.getConnection("") 或 DriverManager.getConnection("","","") 进行单元测试
- r - 行上的R数据帧cumsum
- android - Android,Room 在使用 Robolectric 进行单元测试时失败
- python - UnicodeDecodeError 异常是如何工作的?
- python - miniconda 找不到包
- sql - Oracle REGEXP_COUNT 不转义方括号]
- javascript - 解决快速路线中的承诺
- c# - 如何将下拉列表的多个值从视图发送到控制器
- javascript - 相同表单的多个版本的 Vanilla JavaScript 表单验证