Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In a book I'm reading, linked lists are shown to be created like this:

C++
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 = p_ship;
  return p_ship;
}


What I don't understand is, on the lines:

C++
p_ship->p_next_enemy = p_enemies;
p_enemies = p_ship;

Here when the next enemy is assigned, shouldn't it take the address value of the next enemy so it should look like this:

C++
p_ship->p_next_enemy = &p_enemies;
p_enemies = p_ship;


What I have tried:

Nothing........................................................
Posted
Updated 2-Mar-18 11:55am
v2

A quick recap on pointers in C++:
C++
EnemySpaceShip* ship; //defining a pointer "ship"
ship; //the pointer (address of value)
*ship; //the value
&ship; //the address of the pointer, the value returned is EnemySpaceShip**
       //(pointer to a pointer)

What your function is doing is inserting the new ship at the front of the existing ship list by creating a new ship (p_ship), linking the existing ship list (p_enemies) to the new ship, then setting the ship list pointer to the new ship.

So yes it should take the address of the enemy ship list which it does. Using & would be taking the address of the address of the enemy ship list.
 
Share this answer
 
v2
Comments
BerthaDusStuf 7-Mar-18 3:51am    
Thanks for the reply. I dont think it would take the address of the list but it would just take the address of that ship because each ship has its own individual address but I now can see how it would work without taking the address of the pointer.
Look at how p_enemies is declared, and it's probably declared as a pointer.

You wouldn't say &p_enemies because p_enemies is already a pointer. You don't need to take the address of the pointer. In fact, it would crash the program, because when you attempt to dereference the address of the pointer, it would point (likely) to unallocated memory.
 
Share this answer
 
Comments
BerthaDusStuf 7-Mar-18 3:49am    
hi sorry I took so long to reply, because of school but thanks for your reply, I now understand why it doesn't have to point to the address of the next enemy because that would meant to get the values of the next enemy you would have to dereference twice to get the values of the enemy but I still think it would work if it did, you could just dereference twice to get the values of the enemy and I dont see why it would point to unallocated memory as when p_enemies was declared it would have been given a valid memory address.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900