c++pointersmultiple-indirection

A pointer to an array of pointers


I know I should know this, but it's late and my brain just won't put the pieces together.

This is as straight forward as a question can get:

I have a struct item. I want to create a pointer to an array of pointers to that item type.

Eg.

struct item {
    int data;
    string moreData;
};

I want to have an ArrayPointer that point's to an array. I want that array to contain in each element a pointer to an item.

How do I do this in C++, or more sepcifically where do I need to put how many dereferencing operators? I know how to declare basic (single indirection) pointers and am pretty fluent in their use.

I need information for the following steps if at all possible:

Declaring the ArrayPointer.

Initializing the ArrayPointer with a size s.

Initializing each element of ArrayPointer with new item.

eg:

for(int i = 0; i < s; i++)
    ArrayPointer[i] = // a new item

I feel like as soon as someone posts an answer I'm going to facepalm so hard I break my nose.


Solution

  • If I have understood correctly then you need something like this

    item **ArrayPointer = new item *[s];
    
    for ( int i = 0; i < s; i++ )
    {
        ArrayPointer[i] = new item; { i, "More Data" };
    }
    

    Or

    item **ArrayPointer = new item *[s];
    
    for ( int i = 0; i < s; i++ )
    {
        ArrayPointer[i] = new item;
        ArrayPointer[i]->data = i;
        ArrayPointer[i]->moreData = "More Data";
    }
    

    To free the allocated memory you can in reverse order

    for ( int i = 0; i < s; i++ )
    {
        delete ArrayPointer[i];
    }
    
    delete [] ArrayPointer;
    

    Otherewise if s is a constant then you may simply declare an array of pointers. For example

    item * ArrayPointer[s];
    for ( int i = 0; i < s; i++ )
    {
        ArrayPointer[i]->data = i;
        ArrayPointer[i]->moreData = "More Data";
    }