c ++ SDL矩形应用程序停止工作

c++ SDL rectangle app stops working

我正在尝试使用带有 C++ 的 sdl 在屏幕上获得一个矩形。该文件编译但停止工作并且 returns 255。你能给我推荐更好的东西吗?

代码如下:

  SDL_Window* window;

  SDL_Rect* SrcR; //rectangle
  SDL_Rect* DestR; //dist rectangle

  SrcR->x = 0;
  SrcR->y = 0;
  SrcR->w = SHAPE_SIZE;
  SrcR->h = SHAPE_SIZE;

  DestR->x = 100 / 2 - SHAPE_SIZE / 2;
  DestR->y = 50 / 2 - SHAPE_SIZE / 2;
  DestR->w = SHAPE_SIZE;
  DestR->h = SHAPE_SIZE;

  SDL_Init(SDL_INIT_VIDEO);
  window = SDL_CreateWindow("title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 200, 250, NULL);

  SDL_Renderer *renderer = NULL;
  renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
  SDL_Texture *texture = NULL;

  SDL_Surface* surface;
  surface = SDL_GetWindowSurface(window);
  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 0, 0));
  texture = SDL_CreateTextureFromSurface(renderer, surface);

  SDL_RenderClear(renderer);

  SDL_RenderCopy(renderer, texture, SrcR, DestR); //here i got error before

  SDL_RenderPresent(renderer);

您使用的 SDL_Rect 不正确。您已将其定义为一个指针(见下文),但您从未为其分配内存。然后您尝试将值分配给您也未能初始化的 rects,因此可能有任何旧的垃圾地址。

SDL_Rect* SrcR; //rectangle
SDL_Rect* DestR; //dist rectangle

SrcR->x = 0;
SrcR->y = 0;
SrcR->w = SHAPE_SIZE;
SrcR->h = SHAPE_SIZE;

DestR->x = 100 / 2 - SHAPE_SIZE / 2;
DestR->y = 50 / 2 - SHAPE_SIZE / 2;
DestR->w = SHAPE_SIZE;
DestR->h = SHAPE_SIZE;

应该如下:

SDL_Rect SrcR; //rectangle
SDL_Rect DestR; //dist rectangle

SrcR.x = 0;
SrcR.y = 0;
SrcR.w = SHAPE_SIZE;
SrcR.h = SHAPE_SIZE;

DestR.x = 100 / 2 - SHAPE_SIZE / 2;
DestR.y = 50 / 2 - SHAPE_SIZE / 2;
DestR.w = SHAPE_SIZE;
DestR.h = SHAPE_SIZE;

或者你可以直接初始化如下:

SDL_Rect SrcR = {0, 0, SHAPE_SIZE, SHAPE_SIZE};
SDL_Rect DestR = {(50 - SHAPE_SIZE/2), (25 - SHAPE_SIZE/2), SHAPE_SIZE, SHAPE_SIZE};

最后,当调用 SDL_RenderCopy 时,请记住您现在使用的是实例而不是指针,因此您需要传递 rects 的地址:

SDL_RenderCopy(renderer, texture, &SrcR, &DestR);

您绝对应该像评论中提到的那样对 SDL_* 函数进行一些错误检查,尤其是在您从函数获取指针的地方。