adding address of previous element in linked list?

Hi there. In a list I create, I want to add a pointer to both the next element and the previous element. I did part with pointer to next element. But pointer to previous element show "program stopped responding error" when run.
I would really appreciate any kind of help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
struct EnemySpaceShip
{
int x_coordinate;
int y_coordinate;
int weapon_power;
EnemySpaceShip* p_next_enemy;
EnemySpaceShip* p_previous_enemy;
};

EnemySpaceShip* p_enemies = NULL;

EnemySpaceShip* getNewEnemy ()
{
EnemySpaceShip* p_ship = new EnemySpaceShip;
p_ship->x_coordinate = 0;
p_ship->y_coordinate = 0;
p_ship->weapon_power = 20;
p_ship->p_next_enemy = p_enemies;
EnemySpaceShip* p_current=p_enemies;
p_enemies = p_ship;
if(p_current->p_next_enemy!=NULL)
{
    p_current->p_previous_enemy=p_ship;
}
return p_ship;
}

int main()
{
    getNewEnemy();//if i comment this line, i get no error!
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
EnemySpaceShip* getNewEnemy ()
{
    EnemySpaceShip* p_ship = new EnemySpaceShip;
    p_ship->x_coordinate = 0;
    p_ship->y_coordinate = 0;
    p_ship->weapon_power = 20;
    p_ship->p_next_enemy = p_enemies;
    //p_enemies is NULL and so is p_curent
    EnemySpaceShip* p_current=p_enemies;
    p_enemies = p_ship;
    //Dereferencing p_current, accessing NULL pointer, crash
    if(p_current->p_next_enemy!=NULL) {
        p_current->p_previous_enemy=p_ship;
    }
    return p_ship;
}
yes. p_current == NULL; so you can't do p_current->p_next_enemy
It's fixed. Thanks guys!
Topic archived. No new replies allowed.