首页 > 解决方案 > 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 = { ... }; 
}

标签: cc99designated-initializer

解决方案


由于无法在 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您认为最合适的任何内容,这主要是为了说明这一点。只要数组大小是恒定的(因为它们在这里),就没有问题。


推荐阅读