变量的值被覆盖

Value of variable gets overwritten

您好,我正在开发一款使用 C 语言和 SDL2 编写的游戏。我创建了一个播放器结构,它有一个指向 SDL_Rect 的指针。但是好像rect的值被覆盖了,你可以在截图中看到。

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

这是播放器结构:

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);
}

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

  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;