[英]Why can the struct initializer be used after initialization but not the array one?
Struct initializes can be used after initialization by casting it.结构初始化可以在初始化之后通过强制转换使用。 Eg.例如。
struct EST {
int a;
float b;
}est;
int main() {
est = (struct EST){23, 45.4}; //This works nicely and est gets the values
printf("a: %d\nb: %f\n", est.a, est.b);
}
But the same can't be done for arrays:但是对于 arrays 不能这样做:
int arr[6];
arr = (int []){1, 2, 3, 4, 5};
This gives这给
error: assignment to expression with array type错误:赋值给数组类型的表达式
What's more head breaking is that if there is an array in the struct, it still works.更令人头疼的是,如果结构中有一个数组,它仍然可以工作。
struct Weird {
int arr[6];
}w;
int main() {
w = (struct Weird){{1, 2, 3, 4, 5}}; /* It works. The member arr gets all its elements
filled
*/
}
There seems to be something about the =
operator not being valid with arrays after initializing.初始化后, =
运算符似乎对 arrays 无效。 That is my theory.这就是我的理论。
Why is this and how can arrays be assigned after initializing?这是为什么以及如何在初始化后分配 arrays ?
initialization means initializing of a variable at declaration time.初始化意味着在声明时初始化变量。 The following is correct and is supported by 'c':以下是正确的,并受 'c' 支持:
int arr[6] = {1,2,3,4,5,6};
Assignment means assigning a value to a variable somwhere in the program after initialization.赋值是指初始化后在程序中某处给变量赋值。 'C' does not support assignment to a whole array. 'C' 不支持分配给整个数组。 Arrays are very special members in 'c' and are treated in a special way which does not allow assignments. Arrays 是“c”中非常特殊的成员,并以不允许分配的特殊方式处理。
However, you can always copy one array into another either by using a for loop or my using something like memcpy
.但是,您始终可以使用 for 循环或使用memcpy
类的东西将一个数组复制到另一个数组中。 Here is an example:这是一个例子:
int arr[6], brr[6] = {1,2,3,4,5,6};
memcpy(arr,(int[6]){1,2,3,4,5},sizeof(int[6]));
BTW, the cast-like object from your example (int[]){1,2,3,4,5}
is called 'compound literal' and is also allowed in c.顺便说一句,您的示例中的类似铸件的 object (int[]){1,2,3,4,5}
被称为“复合文字”,并且在 c 中也允许使用。 Here it is used to initialize the parameter of the memcpy function.这里用来初始化memcpy function的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.