Heath
Heath

Reputation: 21

How do I initialize a pointer to an array of pointers?

I am trying to initialize a pointer to an array of pointers. Here's an example:

class MyClass { };

// INTENT: define a pointer to an array of pointers to MyClass objects
MyClass* (*myPointer)[];

int main(void) {

  // INTENT: define and initialize an array of pointers to MyClass objects
  MyClass * tempArray [] = {
    new MyClass(),
    new MyClass()
  };

  // INTENT: make myPointer point to the array just created
  myPointer = tempArray;

}

When I compile this I get:

./test2.cpp: In function ‘int main()’:
./test2.cpp:15:19: error: cannot convert ‘MyClass* [2]’ to ‘MyClass* (*)[]’ in assignment
   myPointer = tempArray;
               ^~~~~~~~~

Upvotes: 2

Views: 115

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 595392

An array decays into a pointer to the first element. Since the element type is also a pointer, you can declare a variable that is a double-pointer and have it point at that element, eg:

class MyClass { };

MyClass** myPointer;

int main(void) {

  MyClass * tempArray [] = {
    new MyClass(),
    new MyClass()
  };

  myPointer = tempArray;
    // same as:
    // myPointer = &tempArray[0];

  ...
}

Upvotes: 0

tdao
tdao

Reputation: 17678

// INTENT: define a pointer to an array of pointers to MyClass objects
MyClass* (*myPointer)[];

You can't obmit the size of the array in declaration. You need this:

MyClass* (*myPointer)[2];

Then,

  MyClass * tempArray [] = {
    new MyClass(),
    new MyClass()
  };

  // INTENT: make myPointer point to the array just created 
  myPointer = &tempArray;

Upvotes: 1

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

First, arrays are not pointers. You have to use the address-of:

 myPointer = &tempArray;

Next, when you write

T foo[] = { t1, t2 };

this is just short-hand notation for

T foo[2] = { t1, t2 };

Either use the correct type (Live Example):

MyClass* (*myPointer)[2];

or perhaps better use a std::array<MyClass> in the first place. And forget about raw owning pointers. Use smart pointers instead.

Upvotes: 2

Related Questions