How to use a struct inside another struct?

前端 未结 7 1327
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 21:05

I want to use a nested structure but i dont know how to enter data in it, for example:

struct A {
    int data;
    struct B;
};
struct B {
    int number;
};
         


        
7条回答
  •  臣服心动
    2021-02-05 21:20

    Each member variable of a struct generally has a name and a type. In your code, the first member of A has type int and name data. The second member only has a type. You need to give it a name. Let's say b:

    struct A {
      int data;
      B b;
    };
    

    To do that, the compiler needs to already know what B is, so declare that struct before you declare A.

    To access a nested member, refer to each member along the path by name, separated by .:

    A stage;
    stage.b.number = 5;
    

提交回复
热议问题