c - 在 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");
}
知道我哪里错了吗?干杯:)
解决方案
在这里,您有一个示例如何通过对象或指针访问这些结构/联合。看看最后一个例子。它展示了如何使用匿名结构/联合——它们只需要具有特定的字段名称
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# - EF 代码优先。如何创建自动递增的非索引列?
- sql - “过滤器”处或附近的 Postgres 语法错误
- javascript - 限制字符被添加到 JS 中的元素
- python - 有没有办法组合(连接)一列的不同值?
- javascript - 如何阻止 Json.Parse() 实例化在字符串化对象中找到的类?
- c# - C# 反序列化缺少标签的 XML
- tensorflow - KerasLayer vs tf.keras.applications 性能
- authentication - 登录使用任何密码对用户进行身份验证
- python-3.x - 如何使单选按钮连接到文本文件中的一行并使其显示在框架上
- javascript - React 组件:需要格式化来自 API 响应的地址并将其传递给具有复制到剪贴板功能的组件