Jump to content
  • Advertisement
Sign in to follow this  
Ganoosh_

Double pointers

This topic is 4495 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Yeah, I haven't coded in a while and am getting back onto it, and I forget how to initialize double pointers in C++. For example say foo is a type:
foo pointer**;

pointer = new foo[100];
for (int i=0;i<100i++) {
    pointer = new foo;
}

Basically I need a dynamic array of foo's that I can dynamically create new foo's and delete old foo's in each element. How would I initialize it correctly? The above way doesn't seem to work. Thanks in advance

Share this post


Link to post
Share on other sites
Advertisement

foo** pointer;

// returns a pointer to memory allocated on the heap for 100 pointers
// to foo objects
pointer = new foo*[100];
for (int i=0;i<100;i++)
{
// returns a pointer to memory allocated on the heap for a foo object
pointer = new foo;
}




That should do it.

foo is a pointer to a pointer, so when you dynamically allocate memory, you have to allocate space for pointers to a foo object (which then returns a pointer to a pointer).

Then, in your loop you can go through initializing all of the pointers to foo objects that you just allocated.

Share this post


Link to post
Share on other sites
0) Goes in For Beginners.

1) When declaring a variable, you put a type name and then the variable name. The *'s are part of the type name, so the correct order is foo** pointer. Note however that you don't have to "attach" the *'s to the type name because of C++'s tokenizing rules.

2) If you declare a pointer-to-pointer-to-foo, then that is a pointer to (pointer-to-foo). Therefore a 'new' allocation would have to allocate (a) new pointer-to-foo(s).

3) Please, please don't just do this yourself. Check your options first.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!