Need Help: Problem With Variable Arrays In Classes


Maybe

for (int i=0;i<3;i++) SDL_BlitSurface(myLevel.BG1.BG_gfx, &myLevel.BG1.Frame, screen, myLevel.BG1.Pos);

instead of

for (int i=0;i<3;i++) SDL_BlitSurface(myLevel.BG1.BG_gfx, &myLevel.BG1.Frame, screen, &myLevel.BG1.Pos);

?

Which will give you contents of Pos, instead of the address of pos?

I don't SDL, so I don't know the parameters. The line just seems strange when your allocating a pointer, and then taking the address of it. Maybe I've got the wrong stick...
 
Side note, you have a memory leak in the class of BG (not freeing allocated memory). Consider using std::vector instead.

I can't see anything distinctly wrong with the code. Can you provide a screenshot of the result that you are currently getting?
 
You're declaring a member variable BG1 in level

CODE

class Level{
public:
BG BG1;
Level(void);
};



The a local variable in Level's constructor, so you're not initilising the member variable:

CODE

Level::Level(void){

BG BG1(3);

...
};




What you really want is :

CODE

class Level{
public:
BG *BG1;
Level(void);
};

Level::Level(void){

BG1 = new BG(3);

...
};




or add a separate method
CODE

BG::setInstances(int instances){
Pos = new SDL_Rect[instances];
}

class Level{
public:
BG BG1;
Level(void);
};

Level::Level(void){

BG1.setInstances(3);
...
};




Edit:

or by initialiser list

CODE

class Level{
public:
BG BG1;
Level(void);
};

Level::Level(void) : BG1(3) {



...
};
 
Good spot Parkydr.

To prevent this problem in the future, look at the use of the 'explicit' keyword.

CODE
class BG{
public:
explicit BG (int);
void imgload(char *path);
SDL_Surface *BG_gfx;
SDL_Rect *Pos;
SDL_Rect Frame;
};


Again, I recommend using std::vector over the allocating the array yourself.
 
Back
Top