Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a struct inside another struct?

Tags:

c++

struct

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;
};

So in the main when I come to use it :

int main() {
    A stage;
    stage.B.number;
}

Is that right if not how do i Use it??

like image 893
Shadi Avatar asked Jun 09 '11 02:06

Shadi


1 Answers

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;
like image 129
Rob Kennedy Avatar answered Oct 18 '22 12:10

Rob Kennedy