SDL Error while Creating Window?

2019-07-15 07:51发布

#include<SDL2/SDL.h>
#include<stdio.h>
#include<stdbool.h>

bool init(char *title, int width, int height);
void close();

SDL_Window *window = NULL;
SDL_Surface *screen = NULL;

bool init(char *title, int width, int height){

    bool success = true;

// SDL_Init 0 on success and returns negative on failure
   if( SDL_Init(SDL_INIT_EVERYTHING) != 0 ){
       SDL_Log("Couldn't initialize SDL: %s",SDL_GetError());
       success = false;
   }

// creating Window and Surface
  window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_SHOWN );


// SDL_CreateWindow returns window on creation and NULL on failure
    if ( !window ){
        SDL_Log("Couldn't create window: %s",SDL_GetError());
        success = false;
    } else {
        // get window surface
        screen = SDL_GetWindowSurface( window );
        if ( screen == NULL ){
            SDL_Log("Couldn't get window surface: %s",SDL_GetError());
            success = false;
        }
    }
    return success;
}

void close(){
    // deallocate surface
    SDL_FreeSurface( screen );
    // destroy window
    SDL_DestroyWindow( window );
    // SDL_Quit();
    SDL_Quit();
}

int main(){
    bool running  = true;
    SDL_Event event;
    if( init("My Window", 800, 600) ){
       printf("Congrats\n");
    } else {
        printf("Sorry :(\n");
    }

   while( running ) {
      //  start = SDL_GetTicks();
        while ( SDL_PollEvent( &event ) ){
            switch( event.type ){
                case SDL_QUIT:
                    running = false;
                    break;
            }
        SDL_UpdateWindowSurface( window );
        }
    }

    close();
}

I tried to create a separate function to initialize SDL Window and then tried to attach surface to it but it gave Segmentation fault (core dumped). and sometimes it give the error Info: invalid window too.

If i do not create a separate function and run this code in main function only, it works!

1条回答
叛逆
2楼-- · 2019-07-15 08:56

You forgot to implement a crucial function which is :

SDL_BlitSurface( SDL_Surface* ,const SDL_Rect* , SDL_Surface* , SDL_Rect* );

This functiton can blit the surface and load the data (graphical info) into SDL_Surface Structure.

If you want to learn more detail about this function , You can check out the link.

Link : https://wiki.libsdl.org/SDL_BlitSurface

查看更多
登录 后发表回答