gpt4 book ai didi

c++ - 接收 0xC0000005 : Access violation reading location storing new pointer in pointer array

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

我正在编写一个基本的 Asteroids 程序,使用 SFML 图形库,并且在调试程序时收到错误/崩溃。只有当我试图通过空格键从我的飞船发射一枚 “光子鱼雷” 时才会发生这种情况。这是代码片段。

//check for keypress

if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space) {
for (int index = 0; index < MAX_PHOTONS; index++) {
photons[index] = new SpaceObject(PHOTON_TORPEDO, PHOTON_RADIUS, ship->getLocation(), ship->getVelocity(), ship->getAngle())
photons[index]->applyThrust(PHOTON_SPEED);
std::cout << "LAUNCHING TORPEDO\n";
}
}

// update game objects ------------------------------------------
ship->updatePosition();

for (int index = 0; index < ARRAY_SIZE; index++) {
if (&asteroids[index] != NULL) {
asteroids[index]->updatePosition();
}
}

for (int index = 0; index < MAX_PHOTONS; index++) {
if (&photons[index] != NULL) {
photons[index]->updatePosition();
}
}


// draw new frame ------------------------------------------------
window.clear();
window.draw(background);

for (int index = 0; index < ARRAY_SIZE; index++) {
if (&asteroids[index] != NULL) {
asteroids[index]->draw(window);
}
}

for (int index = 0; index < MAX_PHOTONS; index++) {
if (&photons[index] != NULL) {
photons[index]->draw(window);
}
}

运行代码会导致即时崩溃,调试结果为:

Unhandled exception at 0x00311746 in polygons2.exe: 0xC0000005: Access violation reading location 0x00000018.

我认为错误出在按键事件上。

最佳答案

您的代码有拼写错误。不要使用引用运算符访问对象引用。小行星和光子的元素是对应对象的地址。

 for (int index = 0; index < ARRAY_SIZE; index++) {
if (asteroids[index] != NULL) {
asteroids[index]->updatePosition();
}
}

for (int index = 0; index < MAX_PHOTONS; index++) {
if (photons[index] != NULL) {
photons[index]->updatePosition();
}
}


// draw new frame ------------------------------------------------
window.clear();
window.draw(background);

for (int index = 0; index < ARRAY_SIZE; index++) {
if (asteroids[index] != NULL) {
asteroids[index]->draw(window);
}
}

for (int index = 0; index < MAX_PHOTONS; index++) {
if (photons[index] != NULL) {
photons[index]->draw(window);
}
}

关于c++ - 接收 0xC0000005 : Access violation reading location storing new pointer in pointer array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50383531/

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