0

我在使用野牛联合定义中的结构指针时遇到了一些麻烦,因为我需要这些元素的内存位置,但它们似乎都指向同一个联合位置。不确定我是否使用正确的方式。我的代码如下所示:

主.h:

typedef struct _control *control;
struct _control { ... };

typedef struct _symbol *symbol;
struct _symbol { ... };
...
#include "parser.h"

解析器.y

%{
    #include "main.h"
%}

%union {
    control ctrl;
    symbol s_head;
    symbol s_tail;
}
...
%%
...
%%
int main (int argc, char** argv) {
    ...
    yylval.ctrl = malloc(sizeof(struct _control));
    yylval.s_head = malloc(sizeof(struct _symbol));
    yylval.s_tail = malloc(sizeof(struct _symbol));

    // This will give me the same memory position
    printf("%ld %ld %ld %ld\n",
        yylval, yylval.ctrl,
        yylval.s_head, yylval.s_tail);
    ...
}
4

1 回答 1

0

不确定这是否是正确的方法,但是一旦我将联合元素“转换”为结构,我就将它们映射了。

主文件

typedef struct _control *control;
struct _control { ... };

typedef struct _symbol *symbol;
struct _symbol { ... };

typedef struct _global *global;
struct _global { ... };

解析器.y

%{
    #include "main.h"
%}

%union {
    global g;
}
...
%%
...
%%
int main (int argc, char** argv) {
    ...
    yylval.g->ctrl->some_element ...
    yylval.g->s_head ...
    ...
}

好吧,这行得通。

于 2012-04-17T01:41:50.670 回答