【发布时间】:2019-03-08 14:50:08
【问题描述】:
问题:如果我们有两个不兼容的结构或联合,但是这两种类型的对象具有相同的对象表示的大小 如果我采用其中一种类型的某个对象的对象表示并将其“重新解释”为另一种类型,我会得到未定义/未指定/明确定义的行为。 (我希望措辞不奇怪)。
我的想法:
我提到了结构或联合,因为N6.2.6.1(p6):
结构或联合对象的值永远不是陷阱
另外我发现我们可以将一个对象的值复制到一个char数组6.2.6.1(p4):
可以将值复制到
unsigned char [n]类型的对象中 (例如,memcpy);结果的字节集称为对象 值的表示。
但标准并没有规定我们可以将对象表示复制回来。所以我认为将对象表示复制回具有相同大小表示的类型的对象(即使它不是陷阱)是UB,但我不确定......
示例:
struct test1_t{
int a;
long b;
};
struct test2_t{
int c;
int d;
int e;
int f;
};
int main(){
struct test1_t t1 = {.a = 100, .b = 2000};
struct test2_t t2 = {.c = 1000, .d = 20000, .e = 300000, .f = 4000000};
size_t size;
if((size = sizeof(struct test1_t)) == sizeof(struct test2_t)){
char repr[size];
memcpy(&repr, &t2, size); // since value of structure or union
// is never a trap why don't we treat
// the representation as of some object
// of type struct test_t1
memcpy(&t1, &repr, size);
printf("t1.a = %d\n", t1.a); //t1.a = 1000
printf("t1.b = %d\n", t1.b); //t1.b = 300000
}
}
结果可以用struct test1_tint a;之后的填充来解释。
【问题讨论】:
-
@EOF 正如引用的答案中提到的,我们可以使用
memcpy进行类型双关语,在我的情况下,行为是明确定义的,因为t1已声明类型struct test1_t,这是一个有效的也可以输入。
标签: c struct language-lawyer