简体   繁体   English

C:通过指针设置结构的数组成员

[英]C: setting an array member of a struct through a pointer

I have a struct with an array as a member, and am trying to set that array using arrow syntax. 我有一个数组作为成员的结构,并且正在尝试使用箭头语法设置该数组。 What I have: 我有的:

typedef float Foo[3];
typedef struct {
  Foo foo;
} Bar;

Bar* f() {
  Bar* bar = malloc(sizeof(Bar));
  bar->foo = {1.0, 1.0, 1.0};

  return bar;
}

gcc says: gcc说:

error: expected expression before '{' token

on the line bar->foo = {1.0, 1.0, 1.0}; 在行bar->foo = {1.0, 1.0, 1.0};

I'm at a loss why this doesn't work. 我茫然为什么这不起作用。 Thanks in advance. 提前致谢。

C99 allows it via compound literals: C99通过复合文字允许它:

Bar* f()
{
   Bar* bar = malloc(sizeof(Bar));

   if (bar)
       *bar = (Bar){{1.0, 1.0, 1.0}};

   return bar;
}

The “outer” curlies encapsulate the struct as a whole (if the struct had other members, you'd list them in the outer curlies), and the “inner” curlies are for the array. “外部” curies将整个结构封装起来(如果该结构还有其他成员,则将它们列出在外部curies中),“内部” curies用于数组。

Because C can't copy arrays through assignment. 因为C无法通过赋值复制数组。 The only place that you can ever use the {1.0, 1.0, 1.0} syntax is in the initialization of a variable: 可以使用{1.0, 1.0, 1.0}语法的唯一地方是变量的初始化:

float foo[3] = {1.0, 1.0, 1.0};

It's just not something that the language supports. 语言不支持它。 It's possible that this is because that would allow the = operator to take an indefinite and possibly very long amount of time to perform the copy—it's a philosophical question. 这可能是因为这将使=运算符花费不确定的时间,并且可能花费很长的时间来执行复制-这是一个哲学问题。

It's not a supported syntax. 它不是受支持的语法。 You can only initialize arrays when they are created -- you can't assign to one that is created. 您只能在创建数组时对其进行初始化-您不能分配给创建的数组。

Try 尝试

float bar[3] = {1.0, 2.0, 3.0};
float foo[3];
foo = {1.0, 2.0, 3.0};

That is an example of the difference between initialization and assignment, and there is no assignment operator for arrays in c. 这是初始化和赋值之间区别的一个示例,并且c中的数组没有赋值运算符。

Note however that you can do 请注意,您可以这样做

Bar baz, quix
/* quix get setup some how... */
bar = quix;

because there is an assignment operation on struct s, which is how dreamlax's answer works. 因为对struct有一个赋值操作,这就是dreamlax的答案的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM