我有以下结构安排,并且我正在努力将数据包含在数据的第一个myNestedStruct
部分中。
struct myNestedStruct
{
char programName[28];
union
{
float parameters[1];
struct
{
long size;
char info[1];
} datas;
} contents;
} myNestedStruct;
struct myStruct
{
int ID;
int numIDs;
union
{
myNestedStruct programs[1];
struct
{
int size;
char info[1];
} datas;
} contents;
};
我应该像这样访问它:
myStruct.contents.programs[0].contents.datas
答案 0 :(得分:3)
您的定义不一致。
使用命名的结构,只使用命名的结构:
struct MyNestedStruct /* note: no typedef, but a name */
{
char programName[28];
union
{
float parameters[1];
struct
{
long size;
char info[1];
} datas;
} contents;
};
struct MyStruct /* note: no typedef, but a name */
{
int ID;
int numIDs;
union
{
struct MyNestedStruct programs[1]; /* note the struct */
struct
{
int size;
char info[1];
} datas;
} contents;
};
然后定义一个这样的变量:
struct MyStruct myStruct;
myStruct.contents.programs[0].contents.datas ...;
或使用 typedef匿名结构,只有 typedef' ed匿名结构:
typedef struct /* note: typedef, but NO name */
{
char programName[28];
union
{
float parameters[1];
struct
{
long size;
char info[1];
} datas;
} contents;
} MyNestedStruct;
typedef struct /* note: typedef, but NO name */
{
int ID;
int numIDs;
union
{
MyNestedStruct programs[1]; /* NO struct, as typedef'ed above */
struct
{
int size;
char info[1];
} datas;
} contents;
} MyStruct;
然后定义一个这样的变量:
MyStruct myStruct;
myStruct.contents.programs[0].contents.datas ...;
你可以混合这两种方法,但这样做只会导致混淆。
答案 1 :(得分:0)
结构语法是
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
此处结构标记是可选的。
您的代码中的更改
struct myNestedStruct
{
char programName[28];
union
{
float parameters[1];
struct
{
long size;
char info[1];
} datas;
} contents;
} ; //Removed variable
struct myStruct
{
int ID;
int numIDs;
union
{
struct myNestedStruct programs[1]; //Added struct keyword
struct
{
int size;
char info[1];
} datas;
} contents;
} var; //Declared variable
如何在另一个struct中访问struct
var.contents.programs[0].contents.datas.size = 10 ; //e.g use according to your need