Search code examples
csdlsdl-2

Passing an SDL_Window* struct to a function using address of in C


My goal here is to make creating new mini windows or just separate windows take less code. Instead of:

SDL_Window* window = SDL_CreateWindow("Hello World", 
                                      SDL_WINDOWPOS_UNDEFINED, 
                                      SDL_WINDOWPOS_UNDEFINED,
                                      h, w,
                                      flags);

It would be more like:

SDL_Window* message_box;
createMessageBox(&message_box, "Message Box");

with the function createMessageBox:

void createMessageBox(SDL_Window* message_box, char title[10]) {
    const int MESS_WINDOW_HEIGHT = 240;
    const int MESS_WINDOW_LENGTH = 180;
    
    Uint32 message_box_flags = SDL_WINDOW_SKIP_TASKBAR | SDL_WINDOW_ALWAYS_ON_TOP;
    message_box = SDL_CreateWindow(title, 
                                   SDL_WINDOWPOS_UNDEFINED,
                                   SDL_WINDOWPOS_UNDEFINED,
                                   MESS_WINDOW_HEIGHT,
                                   MESS_WINDOW_LENGTH,
                                   message_box_flags);
}

But my problem is I get an error:

error: cannot convert SDL_Window** to SDL_Window*
createMessageBox(&message_box, "Message Box");
                 ^~~~~~~~~~~~

I have zero idea about what the compiler is talking about here. What is SDL_Window**. I tried looking around online but couldn't find anything about it.

As far as I'm concerned this should work?

Full error:

g++ main.c -w -lSDL2 -o test
main.c: In function int main():
main.c:64:19: error: cannot convert SDL_Window** to SDL_Window*
    createMessageBox(&message_box, "Message Box");
                     ^~~~~~~~~~~~
main.c:12:35: note:   initializing argument 1 of void createMessageBox(SDL_Window*, char*)
    void createMessageBox(SDL_Window* message_box, char title[10]) {
                          ~~~~~~~~~~~~^~~~~~~~~~~
make: *** [Makefile:19: all] Error 1

p.s I already know about SDL_ShowMessageBox that's not really what I'm looking for.


Solution

  • If you want to pass a variable of type SDL_Window* by reference to the function createMessageBox, then you must pass a pointer to that pointer, i.e. you must pass a parameter of type SDL_Window**. So you should change the function parameters

    void createMessageBox(SDL_Window* message_box, char title[10])
    

    to:

    void createMessageBox(SDL_Window** message_box, char title[10])
    

    Now, you can change the line

    message_box = SDL_CreateWindow(title, [...]
    

    to:

    *message_box = SDL_CreateWindow(title, [...]
    

    This will write the return value of SDL_CreateWindow directly into the pointed-to variable in the calling function.

    See these links for a tutorial on the difference between call by value and call by reference: