SDL2 – Why use `SDL_Window* win` and not `SDL_Window win`?


SDL_Window win; will not compile.

SDL_Window is a so-called opaque struct. Somewhere in SDL headers, it’s declared as struct SDL_Window; or something similar (without the body, as opposed to struct SDL_Window {...};). Since you don’t know what members are inside, or even how large the struct is, you can’t create an instance of it.

Somewhere inside of SDL sources (not in the headers accessible to you) there might be a proper definition: struct SDL_Window {...};, which allows SDL itself to create instances of this struct and access its members. But since your code doesn’t see this definition, you can’t do that.

(Disclaimer: I didn’t actually look in the headers. SDL_Window might be typedefed to something like void *, then SDL would have to cast it to a proper struct type before accessing the members, but it’s effectively the same thing.)

This accomplishes several things:

  1. You can’t mess with the the members of this struct, win->foo = bar; won’t compile.

    Technically you could cast the pointer to char * and read/write some bytes to it, but nothing in C/C++ can protect against that.

  2. If you link dynamically, your application is supposed to work with different versions of SDL2.dll. If SDL always handles the (de)allocation of its structs, it’s able to change the size/members of the struct between versions, without your app noticing it.