gpt4 book ai didi

c - 全局 SDL_Renderer* 在函数调用时更改

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

我有全局 SDL_Renderer*,它在函数调用内。

我已经将我的程序简化为这个 MWE,并且问题仍然可以重现。在 GDB 中,您可以在函数和主堆栈帧之间切换,并将变量视为指向 2 个不同的位置。

MWE 来源:

#include <stdio.h>
#include <SDL2/SDL.h>

SDL_Window *gWindow;
SDL_Renderer *gRenderer;

void func() {
SDL_Rect rect = { 100, 100, 100, 100 };
SDL_SetRenderDrawColor(gRenderer, 200, 100, 50, 255);
SDL_RenderClear(gRenderer);
SDL_SetRenderDrawColor(gRenderer, 50, 100, 200, 255);
SDL_RenderFillRect(gRenderer, &rect);
SDL_RenderPresent(gRenderer);
}

int main(int argc, char *argv[]) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *gWindow = SDL_CreateWindow(
"Float",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
300, 300,
SDL_WINDOW_SHOWN
);
SDL_Renderer *gRenderer = SDL_CreateRenderer(
gWindow,
-1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC
);
SDL_SetRenderDrawBlendMode(gRenderer, SDL_BLENDMODE_BLEND);

func();

SDL_DestroyWindow(gWindow);
SDL_DestroyRenderer(gRenderer);
return 0;
}

GDB 输出:

Reading symbols from ./a.out...
(gdb) break 8
Breakpoint 1 at 0x11f0: file test.c, line 8.
(gdb) run
Starting program: /home/oh/code/vania/scrape/a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/usr/lib/libthread_db.so.1".
[New Thread 0x7ffff531f700 (LWP 16701)]

Thread 1 "a.out" hit Breakpoint 1, func () at test.c:8
8 SDL_Rect rect = { 100, 100, 100, 100 };
(gdb) print gRenderer
$1 = (SDL_Renderer *) 0x0
(gdb) frame 1
#1 0x0000555555555318 in main (argc=1, argv=0x7fffffffe7b8) at test.c:31
31 func();
(gdb) print gRenderer
$2 = (SDL_Renderer *) 0x555555763f40
(gdb) continue
Continuing.
[Thread 0x7ffff531f700 (LWP 16701) exited]
[Inferior 1 (process 16697) exited normally]
(gdb) quit

如果我对全局变量的理解是正确的,那么gRenderer应该在所有范围内指向相同的变量。如果我只是误解了全局变量,请原谅我,如果这是问题所在,我在哪里误解了?

最佳答案

您已经声明了具有相同名称但范围缩小的新局部变量;它被称为 shadowing 。如果您不想要,请不要声明新变量,例如:

gRenderer = SDL_CreateRenderer(...);

关于c - 全局 SDL_Renderer* 在函数调用时更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56944971/

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