在C中为数组分配多个值

Uns*_*tal 28 c arrays initialization declaration

有没有办法以浓缩形式这样做?

GLfloat coordinates[8];
...
coordinates[0] = 1.0f;
coordinates[1] = 0.0f;
coordinates[2] = 1.0f;
coordinates[3] = 1.0f;
coordinates[4] = 0.0f;
coordinates[5] = 1.0f;
coordinates[6] = 0.0f;
coordinates[7] = 0.0f;
return coordinates;
Run Code Online (Sandbox Code Playgroud)

有点像coordinates = {1.0f, ...};

Jam*_*ran 26

如果你真的要分配值(而不是初始化),你可以这样做:

 GLfloat coordinates[8]; 
 static const GLfloat coordinates_defaults[8] = {1.0f, 0.0f, 1.0f ....};
 ... 
 memcpy(coordinates, coordinates_defaults, sizeof(coordinates_defaults));

 return coordinates; 
Run Code Online (Sandbox Code Playgroud)

  • 更好的是,将其设置为“静态常量”,编译器可以直接从代码中优化该变量。 (2认同)

dom*_*men 11

有一个技巧可以将数组包装成一个结构(可以在声明后初始化).

即.

struct foo {
  GLfloat arr[10];
};
...
struct foo foo;
foo = (struct foo) { .arr = {1.0, ... } };
Run Code Online (Sandbox Code Playgroud)

  • 四年后我发现它很有用:) (7认同)
  • 哦,好吧......也许有人发现它很有用:-) (3认同)

Pav*_*aev 11

老派方式:

GLfloat coordinates[8];
...

GLfloat *p = coordinates;
*p++ = 1.0f; *p++ = 0.0f; *p++ = 1.0f; *p++ = 1.0f;
*p++ = 0.0f; *p++ = 1.0f; *p++ = 0.0f; *p++ = 0.0f;

return coordinates;
Run Code Online (Sandbox Code Playgroud)