How to make a struct of structs in C++

18,643

Solution 1

Yes, you can. For example, this struct S2 contains an array of four S1 objects:

struct S1 { int a; };

struct S2
{
    S1 the_array[4];
};

Solution 2

Sure, why not.

struct foo {
    struct {
        int a;
        char *b;
    } bar[4];
} baz;

baz.bar[1].a = 5;

Solution 3

Yes, structs can contain other structs. For example:

struct sample {
  int i;
  char c;
};

struct b {
  struct sample first;
  struct sample second;
};
Share:
18,643
neuromancer
Author by

neuromancer

Updated on June 04, 2022

Comments

  • neuromancer
    neuromancer almost 2 years

    Can a struct contain other structs?

    I would like to make a struct that holds an array of four other structs. Is this possible? What would the code look like?

  • Axel Gneiting
    Axel Gneiting almost 14 years
    The struct keyword for declarations isn't necessary for C++
  • James McNellis
    James McNellis almost 14 years
    @Axel: This question is tagged [c]. Correction: This question was tagged [c]. I've edited it to C++ify it; thanks for the heads-up.