I'm learning SDL but I have run across a problem which I can't understand. For some reason, whenever I try to convert an image to the display format it returns a NULL pointer. I've checked the linker and order of functions and everything is right.

Curiously, if instead of trying to optimize the image I just load it and don't optimize, the image appears. Optimizing it does not.

#include<SDL\SDL.h>
#include<SDL\SDL_image.h>

SDL_Surface *cargarImagen(char* imagen);
void aplicarImagen(int x, int y, SDL_Surface *origen, SDL_Surface *destino);

int main(int argc, char *args[])
{
bool quitProgram=0;
SDL_Event event;
SDL_Surface *screen;
SDL_Surface *mensaje;
SDL_Surface *fondo;
SDL_Init(SDL_INIT_EVERYTHING);
mensaje=cargarImagen("mensaje.png");
fondo=cargarImagen("fondo.png");
screen=SDL_SetVideoMode(640,480,32,SDL_SWSURFACE);
while(quitProgram==0)
    {
    SDL_PollEvent(&event);
    if(event.type==SDL_QUIT) {quitProgram=1;}
    if(event.type==SDL_KEYDOWN)
        {
        aplicarImagen(100,100,fondo,screen);
        SDL_Flip(screen);
        SDL_Delay(1500);
        }
    else {aplicarImagen(100,100,mensaje,screen);}
    SDL_Flip(screen);
    }
SDL_FreeSurface(mensaje);
SDL_FreeSurface(fondo);
SDL_Quit();
return 0;
}


SDL_Surface *cargarImagen(char* imagen)
{
SDL_Surface* loadedImage = NULL; 
SDL_Surface* optimizedImage = NULL; 
loadedImage = IMG_Load(imagen); 
if( loadedImage != NULL ) 
    { 
    optimizedImage = SDL_DisplayFormat( loadedImage ); 
    SDL_FreeSurface( loadedImage );
    } 
return optimizedImage;
}


void aplicarImagen(int x, int y, SDL_Surface *origen, SDL_Surface *destino)
{
SDL_Rect aux;
aux.x=x;
aux.y=y;
SDL_BlitSurface(origen,NULL,destino,&aux);
return;
}

Is there anything wrong with the code?

move the statement

screen=SDL_SetVideoMode(640,480,32,SDL_SWSURFACE);

before the function calls to cargarImagen.

So the function returned null because there was no screen surface at all to convert to. I'll have to look at it more carefully next time. Thank you, it works now =)

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.