3

I have a class called "poly". I want to dynamically create an array of pointers to poly objects. The variable "totalPolynomials" holds the number of poly objects.

Here is my code to declare the array:

poly **polyPtr;                         
polyPtr = new poly *[totalPolynomials];

I successfully create poly objects, but don't know how to store their pointers in the array one after another...

2
  • 1
    I suggest to use std::vector<std::unique_ptr<poly>> (or std::vector<poly*>). Commented Apr 20, 2014 at 15:09
  • I would advise against this. Do what @Jarod42 says, instead. Commented Apr 20, 2014 at 15:11

2 Answers 2

4

If you are creating them and then want to store them, you can do something like

poly ** polyPtr;
polyPtr = new poly* [totalPolynomials];

for(int i = 0; i<totalPolynomials; ++i)
{
    polyPtr[i] = new poly(arguments);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You are not actually setting the pointers in the array, so a a demonstration, you would be writing something like this:

poly** polyPtr = new poly*[totalPolynomials];
for(int i = 0; i < totalPolynomials; ++i)
    // You may need to pass constructor arguments here.
    polyPtr[i] = new poly();
    // or polyPtr[i] = myOtherPointer; in case you just wanna share it.

Storing you pointers would be similar instead of allocating memory for new ones. Basically, you would need to replace the new with your pointers.

No answer can go without the warning that you should consider higher-level data and memory management than this when programming in C++ for your productivity and mental well-being.

So, I would suggest using something like this:

std::vector<std::shared_ptr<poly>>

or

std::vector<std::unique_ptr<poly>>

Depending on your exact desire.

1 Comment

I don't think he is trying to create a 2D array, but rather a 1D array of pointers...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.