C99 通过带大括号的指针初始化数组

标签 c c99 designated-initializer

我写了一个函数,它计算一个正方形的所有顶点,给定它的位置和高度。由于不能在 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/

相关文章:

使用 C99 进行 C 结构初始化 - 混合命名和未命名成员是否有效?

c - 将数组设置为一个值

c - strtok() 在 C99 中返回错误值?

c - C90 和 C99 中复合类型对象的对齐

swift - 如何在指定初始化器中调用协议(protocol)扩展初始化器?

ios - 调用父类(super class)指定的初始化程序调用子类

c - 魔数(Magic Number)程序

c++ - 为什么 C 类型泛型表达式不能与 C++ 兼容?

c - 使用 stat 查找文件长度时的错误检查

c - C99/C11 限制类型限定符对没有定义的函数有什么暗示吗?