2013-11-14 21 views
1

考慮下面的結構元素訪問,空指針結構,使用宏

typedef struct tCard { 
    CardClass class; 
    void *proto; 
} Card; 

typedef struct tCardPath { 
    PathType path_type; 
    struct tPath path; 
    Goal goal; 
} CardPath; 

是否有可能訪問由指針指向使用宏,像這樣結構(原)的元素?

((CardPath*)(trial[i].proto))->element1; // this works 
CARD_PROP(trial[i], Path, element1); // the goal 

我嘗試這樣做,但這種編譯時給出error: expected identifier before ‘(’ token

#define PROTO(C) (C).proto 
#define CARD_PROP(C, CARD, PROP) (((Card##CARD *)(PROTO(C)))->(PROP)) 

編輯: 試過了,仍然無法正常工作

#define CARD_PROP(C, CARD, PROP) ((Card##CARD *)(PROTO(C))->PROP 
+0

你的新編輯的宏產生正好'((CardPath *)((trial [i])。proto) - > element1;'。請注意4(和3) – nos

+0

請問爲什麼會這樣? XY問題。http://meta.stackexchange.com/a/66378 – user694733

回答

3

的問題是,你可以」把一個結構的成員放在括號裏。您的宏展開爲:

((CardPath*)(trial[i].proto))->(element1) 
           ^^^^^^^^^^ 

上面標記的位置不應該有括號。