gpt4 book ai didi

c - 声明任何标准变量时 SDL 崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 05:40:19 25 4
gpt4 key购买 nike

这个 SDL 程序工作正常(显示一个窗口并在其上绘制一个位图),但是,如果我在我的程序中声明任何变量(例如 int、long 等),窗口会卡住并且是白色而不是黑色什么也没有画。什么可能导致这种情况?

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

int main(int argc, char* argv[]) {
// line below will cause SDL crash
// int blabla = 640;
SDL_Window *window;
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow(
"A rather exceptional SDL window",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
640,
480,
SDL_WINDOW_OPENGL
);
if (window == NULL) {
printf("Could not create window: %s\n", SDL_GetError());
return 1;
}
SDL_Renderer *renderer;
SDL_Texture *texture;
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Surface *brush;
brush = IMG_Load("brush2.png");
texture = SDL_CreateTextureFromSurface(renderer, brush);
SDL_RenderClear(renderer);
SDL_Rect *sRect, *dRect;
sRect->w = 10;
sRect->h = 4;
sRect->x = 0;
sRect->y = 0;
dRect->w = 10;
dRect->h = 4;
dRect->x = 10;
dRect->y = 10;
SDL_RenderCopy(renderer, texture, sRect, dRect);
SDL_RenderPresent(renderer);
SDL_Delay(1000);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}

最佳答案

您正在写入未分配的内存。

SDL_Rect *sRect, *dRect;
sRect->w = 10; /* w doesn't exist. Writing is undefined behaviour. */

sRectdRect 只是指针。在访问结构成员之前,它们需要指向有效内存。

您可以改为在堆栈中声明它们:

SDL_Rect sRect, dRect;
sRect.w = 10;
sRect.h = 4;
...
SDL_RenderCopy(renderer, texture, &sRect, &dRect);

您还应该检查 SDL_ 函数的返回值。如果这些都失败了,而您无论如何都继续执行,您可能会遇到奇怪的行为或崩溃。

关于c - 声明任何标准变量时 SDL 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20698380/

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