I recently made a switch to SDL as a cross platform alternative to directly accessing DirectX or OpenGL. In an attempt to port a section of my game framework, I encounter logic errors that (to me) make absolutely no sense.

In this snippet, a sprite is simply a wrapper class for an image and a collection of rectangles that makeup sub-images.

// sprite.h

class Sprite
{
private:
	SDL_Surface* surface;
	SDL_Rect* frames;
public:
	SDL_Surface* GetSurface();
	SDL_Rect* GetFrame(int index);
	Sprite(SDL_Surface* surface, SDL_Rect frames[]);
	~Sprite();
};
// sprite.cpp
SDL_Surface* Sprite::GetSurface()
{
	return surface;
}
SDL_Rect* Sprite::GetFrame(int index)
{
	if (frames != NULL)
		return &frames[index];
	else
	{
		SDL_Rect nullFrame;
		nullFrame.x = 0;
		nullFrame.y = 0;
		nullFrame.w = 0;
		nullFrame.h = 0;
		SDL_Rect* frame = &nullFrame;
		return frame;
	}
}
Sprite::Sprite(SDL_Surface* surface, SDL_Rect frames[])
{
	this->surface = surface;
	this->frames = frames;
}
Sprite::~Sprite()
{
	if (frames != NULL)
		delete[] frames;
}

During a test I used 4 rectangles in this format(x position, y position, width, height):
{0, 0, 150, 150}, {150, 0, 150, 150}, {300, 0, 150, 150}, {450, 0, 150, 150}
When accessing any member of an SDL_Rect via Sprite::GetFrame, mostly incorrect values are returned. These rectangles are:
{-15424, 67, 64400, 40}, {150, 0, 150, 150}, {257, 0, 64824, 40}, {450, 0, 150, 150}


Any ideas why this might be?

This

// sprite.h
Sprite(SDL_Surface* surface, SDL_Rect frames[]);
// sprite.cpp
Sprite::Sprite(SDL_Surface* surface, SDL_Rect frames[])
{
...
}

could be the problem. Try using SDL_Rect * frames instead of SDL_Rect frames[].
I don't know if that's a solution because I only use OpenGL, hope this helps though.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.