lundi 28 janvier 2019

passing SDL windows by reference/address

I have recently started trying to learn SDL. I've been following tutorials so far on how to make SDL projects, i wanted to set up the structure for one myself and i didn't want to use global variables for the SDL_Window and SDL_Renderer and any textures. So i declared the window, renderer and texture at the top of main() and passed them to my init() function:

   bool init(SDL_Window* &window, SDL_Renderer* &renderer, const int height, const int width)
{
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        std::cout << "SDL_Init() failed SDL error: " << SDL_GetError() << '\n';
        return false;
    }
    else
    {
        window = SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, 0);
        if (window == NULL)
        {
            std::cout << "SDL_CreateWindow() failed SDL error: " << SDL_GetError() << '\n';
            return false;
        }
        else
        {
            renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
            if (renderer == NULL)
            {
                std::cout << "SDL_CreateRenderer() failed SDL error: " << SDL_GetError() << '\n';
            }
        }
    }

    return true;

}

the caller in main():

if (!init(window, renderer, WINDOW_HEIGHT, WINDOW_WIDTH))
{
    std::cout << "init() failed SDL error: " << SDL_GetError() << '\n';
}

declarations at the top of main():

    SDL_Texture* texture{};
    SDL_Window* window{};
    SDL_Renderer* renderer{};
    int WINDOW_HEIGHT = 480;
    int WINDOW_WIDTH = 640;

as you can see in my init() function, it takes the window and renderer as arguments and puts them into one of these: SDL_Window* &window; initially i tried putting them in : SDL_Window* window; however this would result in the renderer and window being null when the program returned to main(). I don't understand why my initial method did not work but using SDL_Window* &window; does work

As far as i understand window is a pointer (a variable which holds an address) to a SDL struct called SDL_Window and therefore when i pass window to parameter SDL_Window* window, it should give the parameter the address to my window i declared in main() and therefore any changes made to the window in init() should also be made to it in main(), however this was not true and SDL_Window* &window as parameter ended up having the desired effect.

If possible could someone explain why this is.

thank you

Aucun commentaire:

Enregistrer un commentaire