gpt4 book ai didi

c - 了解对象表示

转载 作者:太空宇宙 更新时间:2023-11-04 02:23:06 25 4
gpt4 key购买 nike

<分区>

问题:如果我们有两个不兼容的结构或 union ,但两种类型的对象相同对象表示的大小 如果我采用其中一种类型的某些对象的对象表示并将其“重新解释”为另一种类型,我会得到未定义/未指定/明确定义的行为。 (我希望措辞不奇怪)。

我的想法:

我提到结构或 union 是因为N6.2.6.1(p6):

The value of a structure or union object is never a trap

我还发现我们可以将一个对象的值复制到一个字符数组中6.2.6.1(p4):

The value may be copied into an object of type unsigned char [n] (e.g., by memcpy); the resulting set of bytes is called the object representation of the value.

但是标准并没有规定我们可以将对象表示复制回来。所以我认为将对象表示复制回具有相同大小表示的类型的对象是 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; 后的填充来解释。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com