Thomas
Thomas

Reputation: 2959

Arrays & Pointers

Looking for some help with arrays and pointers and explanation of what I am trying to do. I want to create a new array on the heap of type Foo* so that I may later assign objects that have been created else where to this array. I am having troubles understanding what I am creating exactly when I do something like the following.

Foo *(*f) = new Foo*[10];

Also once I have created my array how do I access each element for example.

(f + 9)->fooMember(); ??????

Thanks in advance.

Upvotes: 0

Views: 270

Answers (4)

fredoverflow
fredoverflow

Reputation: 263058

Arrays and pointers aren't very C++ish. How about

std::vector<std::shared_ptr<Foo> > f;
f.push_back(std::make_shared<Foo>(whatever, arguments, you, need));
// ...
f[9]->fooMember();
// ...

No manual cleanup needed :-)

Upvotes: 1

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

When you have this situation, you might find the following code snippet useful:

First the initialization:

Foo** f = new Foo*[10];
for (int i = 0; i < 10; i++) {
    f[i] = new Foo;
}

Then to access each element in the f array which is what you asked, but you won't be able to do so unless you allocate memory properly for each member by calling the constructor as done above:

f[9]->fooMember();

Finally, to keep things tidy and to prevent memory leaks:

for (int i = 0; i < 10; i++) {
    delete f[i];
}
delete[] f;

Upvotes: 1

James McNellis
James McNellis

Reputation: 354969

Foo *(*f) = new Foo*[10];

The parentheses in the declaration are unnecessary, so this is the same as:

Foo **f = new Foo*[10];

In any case, the new Foo*[10] allocates space for ten Foo*s and leaves them uninitialized. It returns a pointer to the initial Foo* in the array (the zeroth element), which you assign to f.

To access elements of the array, you simply use subscripting:

f[0] = new Foo;
f[0]->fooMember();

Remember that anything you create using new[] must be freed once when you are done with it by calling delete[] on the pointer. For example:

delete[] f;

This does not delete the elements pointed to by the Foo*s in the array. If you create Foo objects using new, you must delete them before you delete the array. For example, to free the element we created above:

delete f[0];

Upvotes: 3

beta
beta

Reputation: 647

You can create an array of pointers using the following code:

Foo** f = new Foo*[10];

Then access the elements with:

f[9]->fooMember();

Be sure to clean up afterwards:

delete[] f;

Thanks.

Upvotes: 1

Related Questions