0

I am trying to learn SDL2 by using C. My problem is that I am trying to avoid creating a global SDL_Window by doing this:

void init(SDL_Window *win){
SDL_Init(SDL_INIT_EVERETHING);
    win = SDL_CreateWindow("PONG", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
}

int main(){
    SDL_Window *window = NULL;
    init(window);
    if(window == NULL) printf("error!");
    
    return 0;
}

The problem is that the window only "exists" in the init function call and the program still prints "error!", indicating that the window in main function is still a null pointer.

If I am doing this directly in main instead it works as supposed to (does not print "error!"):

int main(){
    SDL_Window *window = NULL;
  
    SDL_Init(SDL_INIT_EVERETHING);
    window = SDL_CreateWindow("PONG", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
    if(window == NULL) printf("error!");
    
    return 0;
}

Thanks in advance.

evolhart
  • 1
  • 1
  • 1
    This has nothing to do with SDL. Suppose instead of a `SDL_Window*` you were trying to set the value of a `int*` from `main` in `init`. How would you do that? Or a step further back: What if you wanted to set the value of a `int` variable from `main` in `init`? – user17732522 Jun 03 '23 at 19:41

1 Answers1

2

C implements call by value, so if you pass a variable only their value is actually passed. You could make a 'out'-variable, by passing a pointer to the variable you want to change.

void init(SDL_Window ** win){
    SDL_Init(SDL_INIT_EVERETHING);
    *win = SDL_CreateWindow("PONG", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
}

int main(){
    SDL_Window *window = NULL;
    init(&window);
    if(window == NULL) printf("error!");
    
    return 0;
}

or you are just returning the needed information:

SDL_Window * init(){
    SDL_Init(SDL_INIT_EVERETHING);
    return SDL_CreateWindow("PONG", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
}

int main(){
    SDL_Window *window = NULL;
    window = init();
    if(window == NULL) printf("error!");
    
    return 0;
}
caulder
  • 83
  • 8