c - 分配对象和结构的有效类型

标签 c struct malloc language-lawyer c99

从 c99 的规范来看,我不太明白下面分配对象的有效类型是怎么回事。

typedef struct {
    int x;
    char y;
} MyStruct ;

MyStruct *make_struct (void) {
    MyStruct *p = malloc(sizeof(MyStruct));
    p->x = 1;
    p->y = 2;

    /* what is the effective type of the allocated object at this point? */

    return p;
}

当你给分配的对象赋值时,分配对象的有效类型变成了用于存储的左值类型,但是这里使用的左值是什么?

据我了解,从 6.5.2.3p4..​​.

A postfix expression followed by the -> operator and an identifier designates a member of a structure or union object. The value is that of the named member of the object to which the first expression points, and is an lvalue. If the first expression is a pointer to a qualified type, the result has the so-qualified version of the type of the designated member.

...“x->y”表达式的类型是 y 的类型(但前提是 x 指向限定类型​​)。
那么我有一个没有有效类型的分配对象和两个类型为 int 和 char 的“内部对象”?

多么困惑..

编辑: 假设 *p 的有效类型最终为 int。那么这是未定义的行为吗?有人最终会通过类型为 MyStruct 的左值访问该对象。访问成员是否也意味着访问聚合类型? 这一直在给予..

最佳答案

引用自 C99 6.5/6

The effective type of an object for an access to its stored value is the declared type of the object, if any.

  • malloc(sizeof(MyStruct));此时返回的数据没有有效类型。
  • MyStruct *p = malloc(sizeof(MyStruct)); 仍然没有有效类型,p 只是指向数据,没有存储任何东西。
  • p->x = 1;有效类型规则:

    If a value is stored into an object having no declared type through an lvalue having a type that is not a character type, then the type of the lvalue becomes the effective type of the object for that access and for subsequent accesses that do not modify the stored value.

    因为我们有 int x; 表达式 p->x = 1; 的左值是 int 并且它成为有效类型p->x 中存储的内容。

  • p->y 的情况下,用于对象访问的左值是字符类型,因此上述规则不适用。它也不是作为字符数组复制的。我们以规则的最后一句话结束:

    For all other accesses to an object having no declared type, the effective type of the object is simply the type of the lvalue used for the access.

    意味着 p->y 的有效类型变为 char,因为表达式 p->y = 2; 的左值是字符.

6.5.2.3/4 在这里没有相关性,除了“...并且是一个左值”。

*p 本身没有有效类型,因为我们从未通过完整的结构类型访问内存区域。然而,像 MyStruct m = *make_struct(); 这样的表达式仍然是明确定义的,因为严格的别名规则允许结构访问对象,前提是该结构包含与有效类型。在这种情况下,该结构包含 intchar 成员,它们与数据通过 p->x 引用的有效类型完全兼容和 p->y 结束了。

关于c - 分配对象和结构的有效类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54446877/

相关文章:

c - 使用 cvSaveImage 保存 IplImage(不是 IplImage*)

c -/proc/pid/stat 中文件名的奇怪行为

c - 如何处理高位数字的计算?

c - learn c hard way章节堆和栈代码

c - 在 C 中的结构内部分配指针?

c++ - C++Builder 6 中的最大内存分配

c - 子控件是否在父窗口之后绘制?

struct - 在 Rust 中是否保证了 struct 字段的初始化顺序?

c - 为结构分配内存时出现问题

c - ANSI C 在创建结构时必须使用 malloc() 吗?