Structures containing pointers
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???
In that case, use either sprite1->layer[0] or sprite1[0].layer[0].
As a side note, I abhor the C language.
As a side note, I abhor the C language.
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.
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;
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;
Stiffler is correct, but you would want to have a much better reason that "wanting to use the -> operator" to approach it like that.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement