在结构中初始化 typedef 数组

Initializing typedef arrays in structs

我正在制作一个相机结构。该结构使用 vec3 定义为 typedef float vec3[3].

要初始化 vec3 我做 vec3 vector = {0.,0.,0.};

我的 Cameras 结构是这样的:

typedef struct Cameras {
    vec3 eye;
    vec3 target
} Camera;

但当我这样做时:

Camera cam;
cam.eye = { .5, 1., 0. };

它崩溃了,编译器告诉我:expression must be modifiable

我认为这是指针错误但不是,将 vec3 eye 替换为 vec3 * eyecam->eye = {.5,1.,0.} 没有任何改变。

我是不是以错误的方式创建了结构,或者这是一个非常常见的问题 C 而我只是瞎了眼?

这里我的目标不仅是初始化数组,而且还访问数据并在创建后 modifing/passing 进入函数。

因为cam行定义后,后面的"assignments"不再是初始化.

初始化一个实例,您必须将"assignment"放在定义它的相同位置:

Camera cam = { {.5, 1., 0.} };

或指定成员:

Camera cam = { .eye = {.5, 1., 0.} };

请注意,这也会自动零初始化 cam.target,因为没有为其指定初始值。

我个人更喜欢 "descriptive" 初始化 - 我喜欢指定成员 - 代码更易于人类阅读。

typedef float vec3[3];

typedef struct Cameras {
    vec3 eye;
    vec3 target;
} Camera;

Camera c = 
{
  .eye = {1.0, 2.0, 3.0},   
  .target = {4.0, 5.0, 6.0},   
};

Camera c1 = 
{
  .target = {4.0, 5.0, 6.0},   
};

Camera c2 = 
{
  .eye = {1.0, 2.0, 3.0},   
};

您得到的错误很明显,vec3 的类型是 float [3] - 数组类型,您当然不能“分配”给数组类型。

您可以使用 in another answer. However, with a small trick, you'll be able to use the assignment, also. This would need the usage of a pointer and compound literal 提到的初始化。

您需要将 typedef 更改为 vec3

 typedef float* vec3;

使其成为 float * 然后,您可以使用复合文字来分配值,例如

cam.eye = (float [3]){ .5, 1., 0. };
cam.target = (float [3]){ .45, 2.5, 0.9 }; // just some other values.

使用这种方法的主要好处是,您不仅限于“初始化”,您可以随时执行赋值。

P.S. - ,所以你不会失去任何操作能力。

P.P.S.

引用 C11,章节 §6.5.2.5/ P12

"/tmp/fileXXXXXX" 
 (char []){"/tmp/fileXXXXXX"} 
 (const char []){"/tmp/fileXXXXXX"} 

The first always has static storage duration and has type array of char, but need not be modifiable; the last two have automatic storage duration when they occur within the body of a function, and the first of these two is modifiable.