[英]Pointer of type union (which also contains a struct) to an array of floats C
[英]Dynamic array with struct that contains a union in 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;
}
}
t_struct.obj[j].s_obj
是聯合,不是實際的結構。 您必須使用t_struct.obj[j].s_obj.s1
等。
除非需要每個結構的副本,否則使用指針代替:
struct1 *s1;
// ...
s1 = &t_struct.objs[j].s_obj.s1;
請注意,您還必須指定並集的元素。
訪問結構中包含的並集成員時,一般語法為
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.