结构体和结构体的第一个成员之间的指针别名 [英] Pointer aliasing between struct and first member of struct

查看:39
本文介绍了结构体和结构体的第一个成员之间的指针别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C 中的指针别名通常是未定义的行为(因为严格别名),但 C11 标准似乎允许将指向结构的指针和指向结构的第一个成员的指针进行别名化

Pointer aliasing in C is normally undefined behavior (because of strict aliasing), but C11 standard seems allow aliasing a pointer to struct and a pointer to the first member of the struct

C11 6.7.2.1 (15)...指向结构对象的指针...指向其初始成员...反之亦然...

C11 6.7.2.1 (15)...A pointer to a structure object... points to its initial member... and vice versa...

那么下面的代码是否包含未定义的行为?

So does the following code contain undefined behavior?

struct Foo {
    int x;
    int y;
};

// does foe return always 100?
int foe() {
    struct Foo foo = { .x = 10, .y = 20 }, *pfoo = &foo;
    int *px = (int*)pfoo; *px = 100;
    return pfoo->x;
}

推荐答案

这段代码是正确的.尽管措辞各不相同,但所有版本的标准 C 和 C++ 都允许这样做.

This code is correct. All versions of Standard C and C++ allow this , although the wording varies.

没有严格的别名问题,因为您通过 int 类型的左值访问 int 类型的对象.当执行访问的左值与存储在内存位置的对象具有不同类型时,可能会应用严格的别名规则.

There's no strict aliasing issue because you access an object of type int via an lvalue of type int. The strict aliasing rule may apply when the lvalue doing the access has a different type to the object stored at the memory location .

您引用的文本涵盖了指针转换实际上指向了 int 对象.

The text you quoted covers that the pointer cast actually points to the int object.

这篇关于结构体和结构体的第一个成员之间的指针别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆