sdl 2 - How to properly pass a pointer to a function in C++ for another function operating directly on that pointer? -
i learning create c++ applications using sdl2 library , encountered problem while trying organise code.
here's simple example ilustrating situation:
void createwindow (sdl_window *gamewindow) { gamewindow = sdl_createwindow(/* arguments here */); } int main (int argc, char* argv[]) { sdl_window* gamewindow = null; createwindow(gamewindow); // code here... }
why doesn't work? when try compile code, sdl_geterror() screams: "invalid renderer".
when make way
sdl_window* createwindow (sdl_window* gamewindow) { gamewindow = sdl_createwindow (/* arguments here*/); return gamewindow; }
it works. don't way.
i may not understand pointers or way sdl2 works on them, thought passing 1 function lets me operate directly on variables intead of copies, don't have return anything. me looks operating on copy of variable adress, not variable itself.
arguments in c passed value, is, arguments copied , every modification applied arguments in function alters value of that copy, not passed argument.
resolve problem by
passing reference pointer:
void createwindow (sdl_window*& gamewindow) { gamewindow = sdl_createwindow(/* arguments here */); }
passing pointer pointer. watch out: c-ish , bad c++ code!
void createwindow (sdl_window** gamewindow) { *gamewindow = sdl_createwindow(/* arguments here */); }
returning pointer:
sdl_window* createwindow() { return sdl_createwindow(/* arguments here */); }
Comments
Post a Comment