2012-12-05 50 views
0

我對C很陌生,所以請耐心等待。 我有一個包含可變大小的其他結構的工會這樣的結構:動態數組,結構中包含一個聯合C

typedef struct _obj_struct { 
    struct_type type; 
    union obj { 
     struct1 s1; 
     struct2 s2; 
     struct3 s3; 
    } s_obj; 
} obj_struct; 

typedef struct _t_struct { 
    unsigned int number_of_obj; 
    obj_struct* objs; 
    other_struct os; 
    unsigned int loop; 
} t_struct; 

的struct_type是我們在聯合使用結構類型。 我如何瀏覽objs中的所有元素? 這是做到這一點的正確方法:

struct1 s1; 
struct2 s2; 
struct3 s3; 

for (j=0; j<t_struct.number_of_obj; j++) 
{ 
    switch (t_struct.obj[j].type) { 
     case STRUCT1: 
      s1 = t_struct.objs[j].s_obj.s1; 
      break; 
     case STRUCT2: 
      s2 = t_struct.objs[j].s_obj.s2; 
      break; 
    } 
} 
+0

非常困惑:你必須定義'STRUCT1'和'STRUCT2'然後就可以使用 –

+0

你可能會需要有使用'S3 = t_struct.obj爲STRUCT3的情況下, [j] .s_obj.s3;',據推測。 –

回答

1

除非你需要每個結構的複製,使用指針來代替:

struct1 *s1; 
// ... 
s1 = &t_struct.objs[j].s_obj.s1; 

請注意,您必須指定工會的元素爲好。

1

t_struct.obj[j].s_obj是工會,而不是實際的結構。你必須使用t_struct.obj[j].s_obj.s1

+0

是的,當我複製代碼時,我錯位了。已經修復,謝謝。 – talon

1

當訪問包含在結構內部工會成員,一般的語法是

structVariable.unionVariable.memberName 

你所訪問是好的,如果你只是在末尾添加的成員名稱的方式。所以,正確的版本是:

switch (t_struct.objs[j].type) { 
    case STRUCT1: 
     s1 = t_struct.objs[j].s_obj.s1; 
     break; 
    case STRUCT2: 
     s2 = t_struct.objs[j].s_obj.s2; 
     break; 
} 
相關問題