Dienstag, 30. Dezember 2008

Array of pointers to objects

Well this does seem to be an easy task, but it wasn't obvious to me how to do this. I used this for a producer-consumer-pattern. The producer did allocate objects, and should place their pointers into a fifo. The consumer is suppose to take the object pointer from the fifo.

So I had to create an array of pointers to my objects, but how is this dynamically done?

The first idea was that I needed a pointer to pointer type, holding my array:

MyObject** ppMyObjectArray = 0;

So far so good. I wanted to allocate the size of the array dynamically and thought, to assign it to the dereferenced pointer:

*ppMyObjectArray = new MyObject[m_iArraySize];

However this would be wrong, because I would create an array of objects, instead of an array of pointers to objects. I did have to sneak a little in the web... but found something that is working, which I haven't seen or read anywhere before:

ppMyObjectArray = new MyObject*[m_iArraySize];

The above does allocate an array of pointers of type MyObject. Once you know how to do it, it's obvious, but again I haven't read a book or article so far were I was able to read something like this.

Have fun...