[英]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.