我对C1x中的匿名结构有点困惑。经过适当转换的结构指针指向其第一个成员的规则是适用于初始匿名结构,还是仅适用于初始匿名结构的初始成员?特别是,这个程序在C1x中有意义吗?
#include<stdio.h>
struct node {
struct node *next;
};
/* Does C1x even allow this? Do I have to define struct node inside of inode?
* Are anonymous struct members even allowed to have tags?
*/
struct inode {
struct node;
int data;
};
int main(void) {
inode node1 = {NULL, 12};
inode *ihead = &inode;
node *head = (struct node *)ihead;
/* These should work since struct inode's first member is a struct node. */
printf("Are these equal? %c", head == &node1.next ? 'Y' : 'N');
printf("Is next NULL? %c", head->next == NULL ? 'Y' : 'N');
return 0;
}This回答表明,我可能问的是未命名的结构,而不是匿名结构。我完全误解了匿名结构的本质吗?
发布于 2011-09-10 22:07:35
/* Does C1x even allow this? Do I have to define struct node inside of inode?
* Are anonymous struct members even allowed to have tags?
*/
struct inode {
struct node;
int data;
};首先,struct node成员不是匿名的。它是未命名的,但因为它有一个标记(node),所以它不满足C1x对“匿名”的定义。
除此之外,这显然是C1x语法所允许的。因为SO并不真正支持下标,所以我用方括号标记了可选元素;我还省略了不必要的语法规则,以确保这是有效的:
type-specifier:
struct-or-union-specifier
struct-or-union-specifier:
struct-or-union [identifier] { struct-declaration-list }
struct-or-union:
struct
union
struct-declaration-list:
struct-declaration
struct-declaration-list struct-declaration
struct-declaration:
specifier-qualifier-list [struct-declarator-list];
specifier-qualifier-list:
type-specifier [specifier-qualifier-list]还有4个约束需要满足,但它们都不适用于未命名的成员,因此这是语法上有效的C。
现在,让我们来看看你真正的问题。C1x说:
指向结构对象的指针,经过适当转换后,指向其初始成员(...),反之亦然。
句号。否“除非该成员未命名”。因此,指向node1的指针也是指向未命名的初始成员的指针,也是指向node1.next的指针。然而,在这里,它开始变得有点模糊。可能是我简单地忽略了一个子句,但似乎C1x只说了:
匿名结构或联合的成员被视为包含结构或联合的成员。
我找不到语言说一个未命名的结构的成员被认为是包含结构的成员。这实际上可能是除了指针双关之外,没有保证访问next的方法。我会写信给委员会中的一些人,要求澄清这一点。
您还可能在初始化时遇到问题:
结构对象的未命名成员即使在初始化之后也具有不确定的值。
发布于 2011-09-13 18:27:02
尝试使用node作为类型名称。避免再次声明"struct node“。
struct inode {
node n;//node is a already a defined type name, n is the var name
int data;
};https://stackoverflow.com/questions/6924340
复制相似问题