gpt4 book ai didi

c - SDL_FillRect 中的段错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:30 26 4
gpt4 key购买 nike

我正在使用 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;
}

最佳答案

你得到段错误,因为 surface 仍然是 NULL

此示例代码直接取自 SDL wiki (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));

关于c - SDL_FillRect 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44184864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com