tags:

views:

130

answers:

3

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?

+1  A: 

Sure, why not.

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

baz.bar[1].a = 5;
qrdl
+5  A: 

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];
};
James McNellis
The struct keyword for declarations isn't necessary for C++
Axel Gneiting
@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.
James McNellis
+1  A: 

Yes, structs can contain other structs. For example:

struct sample {
  int i;
  char c;
};

struct b {
  struct sample first;
  struct sample second;
};
sth