我目前正在使用 C++ 编写游戏并使用 SDL 2.0 库。
我正在尝试从纹理中分离出 32x32 图像以存储为图 block ,并尝试从纹理的像素中重新创建它。当我运行这段代码并尝试通过 for 循环编辑 Uint32* 时,我可以编辑它,但是一旦我尝试创建图像,我就会遇到堆损坏。
我目前正在运行这段代码:
Uint32* pixels = (Uint32*)m_pSprite->GetPixels();
int pixelCount = (m_pSprite->GetPitch() / 4) * m_pSprite->GetHeight();
int tileOffset = 0;
int spriteSheetOffset = 0;
int widthOffset = m_pSprite->GetWidth();
Uint32* tilePixels = new Uint32(32);
for (int y = 0; y < 32; y++)
{
tileOffset = (y * 32);
spriteSheetOffset = (y * widthOffset);
for (int x = 0; x < 32; x++)
{
tilePixels[tileOffset + x] = pixels[spriteSheetOffset + x];
}
}
int tilePitch = 32*4;
SDL_Texture* texture = SDL_CreateTexture(backBuffer.GetRenderer(), SDL_PIXELFORMAT_RGB888, SDL_TEXTUREACCESS_TARGET, TILE_WIDTH, TILE_HEIGHT);
我可以看到 Uint32* 变量有问题,这显然不是最佳实践,但我仍在思考什么可以做什么,什么不能做,什么是最好的方法等。
有人对可能发生的事情有解释吗?
最佳答案
Uint32* tilePixels = new Uint32(32);
这是动态分配单个 Uint32
,并将其初始化/构造为值32
。看起来你想要一个 32*32 的数组。试试这个:
Uint32* tilePixels = new Uint32[32*32]; // brackets allocate an array
虽然,由于数组的大小是静态的(在编译时已知),最好只使用堆栈分配的数组而不是动态数组:
Uint32 tilePixels[32*32];
看看是否可以解决问题。
关于C++ - UInt32 上的堆损坏*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40825988/