在c中将数组转换为结构,反之亦然 [英] Cast an array to a struct and vice-versa in c
问题描述
设为以下结构:
typedef struct {
int x;
int y;
} st;
我可以将int数组投射"到结构体st:
I can "cast" an int array to a struct st:
st z;
int t[2];
t[0] = 0;
t[1] = 1;
z = *(st*)(t);
printf("%d,%d\n", z.x, z.y);
然后输出,除了:
0,1
但是我不能将一个结构体st转换为一个int数组:
But i cant cast a struct st to an int array:
st z = {0, 1};
int t[2];
t = *(int*)(&z);
因为初始化后无法分配数组.
since an array cant be assigned after initialization.
那么,我该如何实现呢?感谢您的帮助.
So, how may i achieve this ? Thanks for helping me.
推荐答案
z = *(st*)(t);
从语法上讲,此代码将编译(分配给 struct
),并且由于违反严格的别名要求,可能会产生预期或意外的结果.
Syntactically this code will compile (assignation to struct
) and may give the expected or unexpected result because it violates strict aliasing requirement.
t = *(int*)(&z);
由于多种原因,这段代码在语法上是不正确的,因此编译本身将失败.首先,您无法分配给数组,其次,您正在将指向 int
的指针分配给 int
数组.更好的选择是使用 memcpy
或 union
.虽然我建议按会员副本.
This piece of code is syntactically incorrect for multiple reasons and thus compilation itself would fail. First of all, you can't assign to arrays, secondly, you are assigning a pointer to int
to an int
array. A better bet would be to use memcpy
or union
instead. Though I would suggest member by member copy.
这篇关于在c中将数组转换为结构,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!