2017-05-25 43 views
1

我使用SDL2庫,在C.段錯誤的SDL_FillRect

我做了一個測試程序,打開一個白色窗口,但我得到的功能SDL_FillRect分段錯誤,即使沒有任何錯誤或警告當我建立它。

下面的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <stdbool.h> 
#include <SDL2/SDL.h> 
#include <SDL2/SDL_image.h> 
#include <SDL2/SDL_ttf.h> 

static const int window_width = 1000; 
static const int window_height = 1000; 

int main(int argc, char* argv[]) 
{ 
    //Window 
    SDL_Window *window = NULL; 

    //Window Surface where things will be shown 
    SDL_Surface *surface = NULL; 

    //Inicializar SDL 
    if(SDL_Init(SDL_INIT_VIDEO) == -1) 
    { 
     printf("Failed to initialize SDL2. SDL Error: %s", SDL_GetError()); 
    } 
    else 
    { 
     window = SDL_CreateWindow("Test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, window_width, window_height, SDL_WINDOW_SHOWN); 
     if(window == NULL) 
      printf("Failed to create SDL2 window. SDL Error: %s", SDL_GetError()); 
     else 
     { 
      //Fill window with white color 
      SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 0xFF, 0xFF, 0xFF)); 
      //Update surface with new changes 
      SDL_UpdateWindowSurface(window); 
      //Wait before closing (parameter in miliseconds) 
      SDL_Delay(4000); 
     } 
    } 
    SDL_DestroyWindow(window); 
    SDL_Quit(); 

    return 0; 
} 
+0

您正在傳遞**表面**(它被設置爲** NULL **)作爲第一個參數到SDL_FillRect,可能是問題https://wiki.libsdl.org/SDL_FillRect – smcd

+0

嗯,好的。那麼我應該怎麼傳遞它呢? –

+0

按照鏈接中的示例代碼所示創建曲面。 ** SDL_Surface * surface = SDL_CreateRGBSurface(0,window_width,window_height,32,0,0,0,0); ** – smcd

回答

1

你得到分割的錯,因爲surface仍然NULL

直接從SDL維基(https://wiki.libsdl.org/SDL_FillRect)採取此示例代碼演示瞭如何調用SDL_FillRect()

之前創建一個 SDL_Surface
/* Declaring the surface. */ 
SDL_Surface *s; 

/* Creating the surface. */ 
s = SDL_CreateRGBSurface(0, width, height, 32, 0, 0, 0, 0); 

/* Filling the surface with red color. */ 
SDL_FillRect(s, NULL, SDL_MapRGB(s->format, 255, 0, 0)); 
+0

感謝您的幫助,我剛剛意識到我在SDL_FillRect之前忘記了SDL_GetWindowSurface函數。不知道這個和SDL_CreateRGBSurface有什麼區別(後者沒有完全解決問題:不會顯示錶面,雖然它確實結束了段錯誤),但會深入研究它。 我遵循本教程,以防有人感興趣: http://lazyfoo.net/tutorials/SDL/01_hello_SDL/index2.php –