Sign in to follow this  
Thomo

Structures containing pointers

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
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[i] = 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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this