【问题标题】:struct within struct in cc语言结构中的结构
【发布时间】:2011-09-09 18:39:20
【问题描述】:

我想在一个结构中访问一个结构,有人知道怎么做吗?

编辑:

typedef struct{
    int a, b;
} struct_1;

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

这里例如我想给 Table[0].exemple.a 赋值

谢谢。 编辑:哇,我真是个笨蛋.. 有时它只是我的打印打印了 100 次,而我只有 6 个条目,所以我只需要查看打印,谢谢

【问题讨论】:

  • Table[0].exemple.a = value; 有什么遗漏吗?

标签: c arrays structure


【解决方案1】:

和你的例子一模一样:

Table[0].exemple.a = 12;

我认为您的问题是 exemple 在您的示例中是 struct_2,而不是 struct_1 就像您想要的那样。试穿它的大小(正确拼写):

typedef struct{
  int a, b;
} struct_1;

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

【讨论】:

    【解决方案2】:

    使用嵌套结构,您可以继续访问属性,直到达到您要查找的内容,如下所示:

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

    【讨论】:

      【解决方案3】:

      我想你的意思可能是:

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

      而不是

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

      因为struct_2 没有a 字段。

      在此之后,例如,Table[0].exemple.a = 5 应该可以工作。

      【讨论】:

        【解决方案4】:

        您对struct_2 的声明看起来有误。将struct_2 exemple; 替换为struct_1 exemple;。要访问结构内的数据,请使用 . 运算符或 -> 运算符(如果您使用指针)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-01-19
          • 2018-06-19
          • 2019-05-02
          • 1970-01-01
          • 1970-01-01
          • 2015-06-07
          • 2021-12-05
          相关资源
          最近更新 更多