views:

90

answers:

3

This is an SDL problem, however I have the strong feeling that the problem I came across is not related to SDL, but more to C++ / pointers in general.

To make a long story short, this code doesn't work (edited to show what I really did):

player->picture = IMG_Load("player");
SDL_BlitSurface(player->picture, NULL, screen, &pictureLocation);

I see nothing on the screen. However, when I do it like this, it works:

SDL_Surface* picture = IMG_Load("player.png");
player->picture = picture;
SDL_BlitSurface(player->picture, NULL, screen, &pictureLocation);

I can see the little guy just fine.

The real problem is that I cannot instantiate Player::picture directly. Even when I try

picture = IMG_Load("player.png")

in player.cpp, I end up with a nullpointer.

A: 

What data type is player->picture? What type does IMG_Load return? It's really hard to come up with a scenario where saving an expression in a temporary variable changes the result, unless a type conversion is involved.

And I wouldn't call this pointer instantiation. You're instantiating an instance of some picture type and storing a pointer to it.

Ben Voigt
IMG_Load returns an SDL_Surface*, and player->picture is also an SDL_Surface*. I think if it wasn't the same type all around, I'd get a compiler error.
aheld
+2  A: 

I am so stupid. Turns out like I forgot the file extension ".png" every time I tried to store the surface in Player::picture, and conveniently remembered to add it every time I stired it in an SDL_Surface declared in main.cpp.

I had the feeling I was overlooking something really simple here, but this is just embarassing. What's a fitting punishment for this?

aheld
:) No punishment necessary. But other answers are right, you should be checking the result for null and handling it properly, not letting it crash from a null. Unless you omitted that for conciseness. In any case, since this is the answer click the green check mark next to it.
GMan
I'm not registered, so I had to wait two days to be able to mark this answer.
aheld
A: 

This is why you should always check to see what IMG_Load() returns...

SDL_Surface* picture = IMG_Load("player.png");
if (picture == NULL) {
  // there was obviously some sort of error.
  // what does SDL_GetError() say?
}

Some SDL functions return -1 if there is an error. Just check the documentation and make sure you're checking your function returns. These steps make debugging a lot easier.

mepcotterell