c - 在 C 中访问 union 体成员的成员

标签 c struct enums

我对 C 有点陌生,我正在尝试访问结构体中 union 体内部结构体的一些成员,而 union 体又位于结构体内部。我尝试过类似 struct.struct.member 但失败了我也尝试使用箭头运算符访问它(将“.”替换为“->”),但它不起作用出色地。 所以就我而言,我试图访问位于“tree_node”结构内部的“程序”。这是结构的代码:

struct tree_node;
typedef struct tree_node node_t;

struct tree_node
{
    enum node_type type;

    union {
        struct {
            char *program;
            char **argv;
            size_t argc;
        } command;

        struct {
            node_t **parts; // array
            size_t n_parts;
        } pipe;

        struct {
            node_t *child;
            int fd; // >= 0 specific fd; -1 stdout+stderr
            enum redirect_type mode;
            union {
                int fd2;
                char *target;
            };
        } redirect;

        struct {
            node_t *child;
        } subshell;

        struct {
            node_t *child;
        } detach;

        struct {
            node_t *first;
            node_t *second;
        } sequence;
    };
};

我当前用来访问“程序”的代码(没有文字)是这样的:

node_t *n

if (n.command.program == "cd")
        {
            printf("cd command entered\n");
        }

知道我哪里出错了吗? 干杯:)

最佳答案

这里有一个如何通过对象或指针访问这些结构/union 的示例。看一下最后一个例子。它展示了如何使用匿名结构/union - 它们只需具有不同的字段名称

void foo()
{
    node_t obj, *ptr;

    ptr -> pipe.n_parts = 5;
    printf("%s\n", ptr -> command.program);

    obj.detach.child = ptr;
    obj.bar = obj.foo;
}

数据结构在这里

struct tree_node;
typedef struct tree_node node_t;

struct tree_node
{
    int type;

    union {
        struct {
            char *program;
            char **argv;
            size_t argc;
        } command;

        struct {
            node_t **parts; // array
            size_t n_parts;
        } pipe;

        struct {
            node_t *child;
            int fd; // >= 0 specific fd; -1 stdout+stderr
            int mode;
            union {
                int fd2;
                char *target;
            };
        } redirect;

        struct {
            node_t *child;
        } subshell;

        struct {
            node_t *child;
        } detach;

        struct {
            node_t *first;
            node_t *second;
        } sequence;

        struct {
            node_t *bar;
            node_t *foo;
        };

    };
};

关于c - 在 C 中访问 union 体成员的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58934863/

相关文章:

c - 如何使用用户输入的结构填充动态数组的元素?

python - Python 中的枚举 : How to enforce in method arguments

wcf - 从 WCF 服务公开未使用的枚举

c - 在结构中保存变量

c - 显示地址给出的字节内容

c++ - memcmp 适用于非平面结构吗?

c++ - ArrayList 无法返回结构

c - C中的随机数

c - 退出函数的 noreturn 属性是否必要?

python - 如何在 Pandas DataFrames 中显示 IntEnum 的名称