gpt4 book ai didi

c - 变量的值被覆盖

转载 作者:行者123 更新时间:2023-11-30 14:43:06 24 4
gpt4 key购买 nike

您好,我正在开发一款用 C 语言和 SDL2 编写的游戏。我创建了一个播放器结构,它有一个指向 SDL_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);
}

最佳答案

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

  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;

关于c - 变量的值被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54137863/

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