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的左值最终访问该对象.访问成员是否意味着访问聚合类型?
这继续给..
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,因为表达式的左值为y-> y = 2;是char.
除了“……并且是左值”之外,6.5.2.3 / 4与此无关.
* p没有这样的有效类型,因为我们从未通过完整的结构类型访问内存区域.但是,表达式如MyStruct m = * make_struct();由于严格别名规则允许对对象进行struct访问,因为struct包含与有效类型兼容的成员,因此仍然是定义良好的.在这种情况下,struct包含int和char成员,这些成员与p-> x和p-> y引用的数据最终的有效类型完全兼容.