简体   繁体   English

c中的struct内的struct

[英]struct within struct in c

I want to access a struct within a struct, does anyone know how? 我想访问结构中的结构,有人知道吗?

EDIT: 编辑:

typedef struct{
    int a, b;
} struct_1;

typedef struct{
    int c;
    struct_1 exemple;
} struct_2;
struct_2 Table[100];

Here for example I want to assign a value to Table[0].exemple.a 例如,在这里我想为Table [0] .exemple.a分配一个值

Thank you. 谢谢。 EDIT: wow im such a dumba.. sometimes it was working iits just that my print was printing 100 times whereas I had just 6 entries so I just had to look up on the print thanks anyway 编辑:哇我真是傻瓜..有时它的工作原理是我的印刷品正在打印100次,而我只有6个条目,所以无论如何我都不得不抬头看看印刷品

Exactly like your example: 完全像您的示例:

Table[0].exemple.a = 12;

I think your problem is that exemple is struct_2 in your example, and not struct_1 like it appears you intended. 我觉得你的问题是, exemplestruct_2在你的榜样,而不是struct_1像它看起来你打算。 Try this on for size (with corrected spelling): 试一下以获取大小(拼写正确):

typedef struct{
  int a, b;
} struct_1;

typedef struct{
  int c;
  struct_1 example;
} struct_2;
struct_1 Table[100];

With nested structs you continue to access the properties until you reach what you are looking for like so: 使用嵌套结构,您可以继续访问属性,直到达到所需的内容为止,如下所示:

Table[0].example.a = 5;
Table[0].example.b = 10;

I think you probably meant: 我想您可能是说:

typedef struct{
    int c;
    struct_1 exemple; /* see how it's struct_1 */
} struct_2;

and not 并不是

typedef struct{
    int c;
    struct_2 exemple;
} struct_2;

Since struct_2 doesn't have an a field. 由于struct_2没有的a领域。

After this, Table[0].exemple.a = 5 , should work, for example. 此后,例如Table[0].exemple.a = 5应该起作用。

Your declaration of struct_2 looks wrong. 您的struct_2声明看起来不正确。 Replace struct_2 exemple; 替换struct_2 exemple; with struct_1 exemple; struct_1 exemple; . To access data inside the structure, use the . 要访问结构内部的数据,请使用. operator or the -> operator if you are using pointers. 运算符或->运算符(如果使用指针)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM