Monkeyanator
Monkeyanator

Reputation: 1416

Making an array of a certain struct within the struct.

I have a structure called scene. Within the structure called scene, I need to make an array of other scene objects. Is this possible?

Upvotes: 2

Views: 102

Answers (4)

Seth Carnegie
Seth Carnegie

Reputation: 75150

No, because before scene is completely defined, the compiler doesn't know how big it is, and doesn't know what size to make the array.

However, you can have an array of pointers to scene, because pointers (not counting pointers to members and other oddities - thanks Nawaz) are all the same size:

class scene {
    scene* array[20];
};

Alternatively, you can store a pointer that will point to a dynamic array allocated with new[] and deallocated with delete[]:

class scene {
    scene() : array(new scene[20]) { }
    ~scene() { delete[] array; }

    scene* array;
};

or even more alternatively, store a vector<scene>, a vector of scenes:

class scene {
    vector<scene> array;
};

and with vector, you get a resizable array with no manual memory management.

Upvotes: 8

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361772

Yes. You can do that. But you've to declare the member as pointer as:

struct scene
{
     //other members

     scene *children; //this is what you need.
                      //you cannot make it like : scene children[100];
};

Then create the dynamic array as:

scene parent;
parent.chidren = new scene[100]; //100 children!

Just remember that you've to allocate and deallocate the memory yourself.

Alternatively, you can use std::vector<scene*>, or boost::ptr_vector<scene>.

Upvotes: 2

DejanLekic
DejanLekic

Reputation: 19822

Sure it is possible.

Pseudocode:

struct Scene {
   int id;
   Scene* scenes;
};

PS. you could easily test this - do not be so lazy. ;)

Upvotes: 0

TonyK
TonyK

Reputation: 17124

You can do it if you use std::vector. This is from some code I wrote yesterday:

#include <vector>
struct ChangeList // Tree of changes in a tree of values
  {
  int index ;
  std::vector<ChangeList> Changes ;
  } ;

Upvotes: 0

Related Questions