gpt4 book ai didi

c++ - SDL_FillRect 中的 SDL2 段错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:58:34 24 4
gpt4 key购买 nike

终端输出:

    > ./a.out 
bla1
Speicherzugriffsfehler

Speicherzugriffsfehler 在德语中的意思基本上是段错误。

当我使用全局变量,或将函数中的代码复制粘贴到 main 中时,它就可以正常工作。我不知道它为什么坏了。

在 Linux Mint 16 上编译:g++ sdl.cpp -lSDL2

源代码:

#include <iostream>
#include <SDL2/SDL.h>

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480

using namespace std;

bool init_SDL(SDL_Window *window, SDL_Surface *windowSurface);
void close_SDL(SDL_Window *window, SDL_Surface *image);

int main(int argc, char *argv[])
{
SDL_Window *window = NULL;
SDL_Surface *windowSurface = NULL;
SDL_Surface *image = NULL;

if(!init_SDL(window, windowSurface)){
cout << "Failed to initialize SDL" << endl;
}
else{
cout << "bla1" << endl;
SDL_FillRect(windowSurface, NULL, SDL_MapRGB(windowSurface->format, 0xFF, 0xFF, 0xFF));
cout << "bla2" << endl;
SDL_UpdateWindowSurface(window);
cout << "bla3" << endl;
SDL_Delay(2000);
}
close_SDL(window, image);

EXIT_SUCCESS;
}

bool init_SDL(SDL_Window *window, SDL_Surface *windowSurface){
bool success = true;
if(SDL_Init(SDL_INIT_VIDEO) < 0){
cout << "SDL failed to initialize! SDL_Error: " << SDL_GetError() << endl;
success = false;
}
else{
window = SDL_CreateWindow("SDL Test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if(window == NULL){
cout << "Failed to create window! SDL_Error: " << SDL_GetError() << endl;
success = false;
}
else{
windowSurface = SDL_GetWindowSurface(window);
}
}
return success;
}

void close_SDL(SDL_Window *window, SDL_Surface *image){
SDL_FreeSurface(image);
SDL_DestroyWindow(window);
SDL_Quit();
return;
}

最佳答案

我在 reddit 上找到了解决方案。这解决了它:

bool init_SDL(SDL_Window *&window, SDL_Surface *&windowSurface)

我需要通过引用传递指针,因为指针本身在函数中被操纵。否则他们仍然会指向 main 中的 null。

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

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