gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:59:18 24 4
gpt4 key购买 nike

我对 C 有点陌生,我正在尝试访问结构内的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com