1

我对 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;
}

这个答案表明我可能在询问未命名的结构而不是匿名结构。我完全误解了匿名结构的性质吗?

4

2 回答 2

3
/* 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-10T14:07:34.893 回答
-1

尝试使用 node 作为类型名称。避免再次声明“结构节点”。

struct inode {
    node n;//node is a already a defined type name, n is the var name
    int data;
};
于 2011-09-13T10:27:02.227 回答