SDL_FillRect

时间:2017-05-25 15:58:50

标签: c debugging segmentation-fault sdl-2

我在C。

中使用SDL2库

我制作了一个打开白色窗口的测试程序,但是我在使用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;
}

1 个答案:

答案 0 :(得分:1)

由于surface仍为NULL

,您会收到细分错误

直接从SDL wiki(https://wiki.libsdl.org/SDL_FillRect)获取的此示例代码显示了在调用SDL_Surface之前如何创建SDL_FillRect()

/* 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));