简体   繁体   English

变量的值被覆盖

[英]Value of variable gets overwritten

Hello I am working on a game written in C with SDL2. 您好,我正在使用SDL2用C编写游戏。 I have created a player struct, which has a pointer to an SDL_Rect. 我创建了一个播放器结构,它具有一个指向SDL_Rect的指针。 But it seems that the value of the rect is being overwritten, which you can see in the screenshot. 但是似乎rect的值已被覆盖,您可以在屏幕截图中看到。

Console of the game, first two logs are the values which it should contain 游戏控制台,前两个日志是应包含的值

Here is the Player struct: 这是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;
}

Here is the main function: 这是主要功能:

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

You are assigning the pointer to a local variable: 您正在将指针分配给局部变量:

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

  player->rect = &rect;

The local variable will be invalid once it goes out of scope (when reaching the end of the function), and any pointer to it will point to invalid memory -> undefined behaviour. 一旦超出范围(到达函数末尾),局部变量将无效,指向该变量的任何指针都将指向无效内存->未定义的行为。

Write ... 写...

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM