Jump to content
  • Advertisement
Sign in to follow this  
Thomo

Structures containing pointers

This topic is 4411 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

I've typdef'd a structure: typedef struct Sprite { LAYER *layer; . . . } SPRITE The layers are the individual animation cells. I have allocated memory for pointers to 100 sprites. The compiler complains about doing this: sprite1[0]->layer[0]; If I change the LAYER definition in SPRITE to: LAYER *layer[10]; The above code works fine. However, I do not want to limit myself to a fixed number of animation frames. To do so, do I need to allocate memory for the layers in sprite too???

Share this post


Link to post
Share on other sites
Advertisement
In that case, use either sprite1->layer[0] or sprite1[0].layer[0].

As a side note, I abhor the C language.

Share this post


Link to post
Share on other sites
Quote:
Original post by Thomo
The compiler complains about doing this:

sprite1[0]->layer[0];

If I change the LAYER definition in SPRITE to: LAYER *layer[10]; The above code works fine.


Are you sure about that? The problem occurs because sprite1 is a pointer, but when you apply [] to it, it dereferences it so it becomes an actual instance so you need . rather than -> to access its members.

I fail to see how changing the types of the members of Sprite could affect this.

Also, I appreciate it is defined as:

Sprite *sprite1;

but what are you then pointing that pointer at? A single sprite or an array of sprites? If the former, you do not need the [0] at all.

Share this post


Link to post
Share on other sites
If you want this code to work, sprite1[0]->layer[0]; You will need to define sprite1 as
Sprite** sprite1;
Then you can dynamically allocate your sprites
sprite1 = new Sprite*[100];
for(int i = 0; i < 100; i++)
{
sprite1 = new Sprite;
}
Now you have an array of pointers... :)

So sprite1[0]->layer[0]; will work as you want.

But be careful, memory leaks come easy here.

To destroy do this

for(int i = 0; i < 100; i++)
{
delete sprite1[0];
}
delete[] sprite1;

Share this post


Link to post
Share on other sites
Stiffler is correct, but you would want to have a much better reason that "wanting to use the -> operator" to approach it like that.

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!