2012-04-15 22 views
0

我在使用指向結構的指針指向Bison的union定義時遇到了一些麻煩,因爲我需要這些元素的內存位置,但它們都是seem to point to the same union position。不知道如果我使用正確的方式。我的代碼如下所示:C和野牛:指向%聯合定義中的結構的指針

main.h:

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

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

parser.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); 
    ... 
} 
+0

在野牛(和它的前身Yacc一樣),'%union'聲明瞭一個C'union',你應該更多地閱讀這些。 – 2012-04-15 15:12:36

回答

0

不知道這是做的正確的方式,但我剛剛我的工會元素映射一次我'轉換'成一個結構。

main.h

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

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

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

parser.y

%{ 
    #include "main.h" 
%} 

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

好吧,這只是工作。