Initialize SDL_Surface* into a function

440 views Asked by At

I want to initialize all my SDL_Surface into a function in order to have the clearest main possible, but it don't seems to work. I'm doing it like this :

void setImages(SDL_Surface* mur, SDL_Surface* caisse, SDL_Surface* caisseOk, SDL_Surface* menu, SDL_Surface* objectif)
{
    mur = IMG_Load("images\\mur.jpg");
    caisse = IMG_Load("images\\caisse.jpg");
    caisseOk = IMG_Load("images\\caisse_ok.jpg");
    menu = IMG_Load("images\\menu.jpg");
    objectif = IMG_Load("images\\objectif.png");
}

And call it in the main like this :

setImages(mur, caisse, caisseOk, menu, objectif);
SDL_BlitSurface(menu, NULL, screen,&posMenu);
SDL_Flip(screen);

I tested, the IMG_Load works properly, but it don't seem to initialize my SDL_Surface outside of the function. Is there a way to do this ? I guess there must be a way to initialize properly all of my SDL_Surface outside of the main...

The same way, if I'm doing the SDL_Init() and SDL_SetVideoMode() into a function, my screen will not be initialize too I guess ? Here's my function :

void initVideo(SDL_Surface* screen)
{
    if(SDL_Init(SDL_INIT_VIDEO) <0)
    {
        fprintf(stderr,"Erreur lors de l'initialisation video : %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    screen = SDL_SetVideoMode(640,420,32,SDL_HWSURFACE | SDL_DOUBLEBUF);
    if(screen == NULL)
    {
        fprintf(stderr,"Erreur lors de la configuration video : %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }
}

And my call into the main :

SDL_Surface *screen = NULL, *menu = NULL, *marioH = NULL, *marioD = NULL, *marioB = NULL, *marioG = NULL,
                *caisse = NULL, *caisseOk = NULL, *objectif = NULL, *mur = NULL;

    SDL_Rect posMenu, posMario;

    initVideo(screen);

Nothing send me an error, but nothing seems to happens. And the only things I found on the net was "Why do you want to do this ? It's useless". Is that right ?

1

There are 1 answers

4
Sourav Ghosh On BEST ANSWER

C uses pass by value for function argument passing.

It seems, your setImages() function changes the argument pointers itself.

Inside setImages() function, you can alter the values pointed by the passed pointers, not the pointers themselves. After returning, in main(), your pointers remain unchanged [uninitialized, if were before the call].

To achieve the desired functionality, you need to pass a pointer to those pointers [the address of those pointers] from your main().

For example, you can change your setImages() function to

void setImages(SDL_Surface** mur, SDL_Surface** caisse, SDL_Surface** caisseOk, SDL_Surface** menu, SDL_Surface** objectif)
{
           //put some NULL check for sanity

    *mur = IMG_Load("images\\mur.jpg");
    *caisse = IMG_Load("images\\caisse.jpg");
   .
   .
}

and call from main() like

setImages(&mur, &caisse, &caisseOk, &menu, &objectif);