簡體   English   中英

訪問 C 中的工會成員的成員

[英]accessing members of members of a union in C

我對 C 有點陌生,我正在嘗試訪問結構內部聯合內部的結構的一些成員。 我嘗試過類似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");
        }

知道我哪里錯了嗎? 干杯:)

這里有一個示例,如何通過 object 或指針訪問這些結構/聯合。 看看最后一個例子。 它展示了如何使用匿名結構/聯合——它們只需要具有特定的字段名稱

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

    };
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM