-1

我对 c++ 相当陌生,想知道为什么我的数组不断损坏。在破坏 ammo_bank 之前,它会经过多次 for 循环,尽管它在该行之前已正确分配。然后它给了我错误写入违规

class bullet{
public:
    int x, y, damage, speed;
    char direction;
};

bullet * ammo_bank[100];
void render(player avatar, riflemen enemy){
    bullet projectile;
    int counter1, counter2, icurrentammo;
    icurrentammo = current_ammo -1;
    for (counter1 = 0; counter1 <=SCREEN_HEIGHT; counter1++){
        for (counter2 = 0; counter2 <=SCREEN_WIDTH; counter2++){     // corruption occurs a few times before here
            screen[counter1][counter2] = '.';
        }
    }
    system("cls");
    screen [avatar.y][avatar.x] = AVATAR_SYMBOL;
    screen [enemy.y][enemy.x] = RIFLEMEN_SYMBOL;
    while (icurrentammo >= 0){
        projectile = *ammo_bank[icurrentammo];                 // Writing error
        screen[projectile.x][projectile.y] = BULLET_SYMBOL;
        projectile.x ++;
        icurrentammo --;
    }

    for (counter1 = 0; counter1 <=SCREEN_HEIGHT; counter1++){
        cout << endl;
        for (counter2 = 0; counter2 <=SCREEN_WIDTH; counter2++){
            cout << screen[counter1][counter2];
        }
    }


void playerShoot(player avatar){
    ammo_bank[current_ammo] = new bullet(); // Create the MyClass here.
    bullet projectile = *ammo_bank[current_ammo];
    projectile.x = avatar.x + 1;
    projectile.y = avatar.y;
    projectile.speed = 2;
    projectile.direction = 'f';
    projectile.damage = 1;
    *ammo_bank[current_ammo] = projectile;
    current_ammo++;
}
4

1 回答 1

2

screen[][] 是如何声明的。如果是 screen[SCREEN_HEIGHT][SCREEN_WIDTH],那么你的问题是你使用 <= 而你应该只使用 <。

于 2012-08-13T20:48:57.613 回答