变量的值被覆盖

时间:2019-01-10 22:32:58

标签: c sdl

你好,我正在用SDL2用C编写游戏。我创建了一个播放器结构,它具有一个指向SDL_Rect的指针。但是似乎rect的值已被覆盖,可以在屏幕截图中看到。

Console of the game, first two logs are the values which it should contain

这是Player结构:

struct Player* createPlayer(int x, int y, int width, int height, SDL_Texture* texture) {
  struct Player* player = (struct Player*) malloc(sizeof(struct Player));
  SDL_Rect rect = {x, y, width, height};

  player->rect = ▭
  player->texture = texture;
  printf("%d\n", player->rect->x);
  return player;
}

这是主要功能:

struct Player* player = createPlayer(0, 0, 128, 128, texture);
bool running = true;
printf("%d\n", player->rect->x);
while(running) {
  SDL_Event event;

  // UPDATE PLAYERS AND STUFF HERE

  while(SDL_PollEvent(&event)) {
    switch(event.type) {
      case SDL_QUIT:
        running = false;

        break;
    }
  }

  SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
  SDL_RenderClear(renderer);

  // RENDER PLAYERS AND STUFF HERE
  printf("%d\n", player->rect->x); <- This is where the different values come from
  SDL_RenderCopy(renderer, player->texture, NULL, player->rect);

  //

  SDL_RenderPresent(renderer);
}

1 个答案:

答案 0 :(得分:1)

您正在将指针分配给局部变量:

  SDL_Rect rect = {x, y, width, height};

  player->rect = &rect;

该局部变量一旦超出范围(到达函数末尾)将无效,指向该变量的任何指针都将指向无效内存->未定义的行为。

写...

  SDL_Rect rect = {x, y, width, height};

  player->rect = malloc(sizeof(SDL_Rect);
  *player->rect = rect;