[英]How to access struct inside another struct
I have the following struct arrangement, and I'mstruggling to get the data contained within the first myNestedStruct
part of the data. 我具有以下结构安排,并且正在努力获取包含在数据的第一个
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;
};
Should I be accessing it like this: 我应该像这样访问它吗:
myStruct.contents.programs[0].contents.datas
Your definitions are not consistent. 您的定义不一致。
Either use named structs, and only named structs: 既可以使用命名结构,也可以仅使用命名结构:
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;
};
Then define a variable like this: 然后定义一个这样的变量:
struct MyStruct myStruct;
myStruct.contents.programs[0].contents.datas ...;
or use typedef'ed anonymous structs, and only typedef'ed anonymous structs: 或使用类型定义的匿名结构,并且仅使用类型定义的匿名结构:
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;
Then define a variable like this: 然后定义一个这样的变量:
MyStruct myStruct;
myStruct.contents.programs[0].contents.datas ...;
You could mix these two approaches, but doing so just leads to confusion. 您可以混合使用这两种方法,但是这样做只会导致混乱。
Structure syntax is 结构语法为
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
Here structure tag is optional. 在这里,结构标记是可选的。
so changes in your code are 所以代码中的更改是
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
How to access struct inside another struct
如何在另一个结构中访问结构
var.contents.programs[0].contents.datas.size = 10 ; //e.g use according to your need
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.