设以下结构:
typedef struct {
int x;
int y;
} st;
我可以将 int 数组“转换”为 struct st:
st z;
int t[2];
t[0] = 0;
t[1] = 1;
z = *(st*)(t);
printf("%d,%d\n", z.x, z.y);
然后输出,如异常(exception):
0,1
但我无法将 struct st 转换为 int 数组:
st z = {0, 1};
int t[2];
t = *(int*)(&z);
因为数组在初始化后无法赋值。
那么,我该如何实现这一目标呢? 谢谢你帮助我。
最佳答案
z = *(st*)(t);
从语法上讲,此代码将编译(分配给 struct
),并可能给出预期或意外的结果,因为它违反了严格的别名要求。
t = *(int*)(&z);
由于多种原因,这段代码在语法上不正确,因此编译本身会失败。首先,您不能分配给数组,其次,您将指向 int
的指针分配给 int
数组。更好的选择是使用 memcpy
或 union
代替。不过我会逐个推荐成员(member)副本。
关于在 c 中将数组转换为结构体,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42268701/