Linked list with pointers

Hello people

I'm reading Alex Allains c++ book and I just got done with pointers to pointers which I had no problems with then we move onto linked lists but this code kind of contradicts the whole need for a pointer to a pointer for example in this code below which I got from the book(variable names have been changed) he does not use pointers to pointers especially p_enemies which is a pointer to hold the ships,the last one holds NULL,well then a pointer nextship points to the pointer p_enemies so technically thats a pointer to pointer situation how come we don't use **nextShip instead of *nextShip,how come this is legal? and since it's legal whats the point of pointers to pointers like this **p?


once I get past this predicament I'll be elated

Thanks

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
33
34
35
36
37
38
39
40



#include <iostream>

using namespace std;


struct ship{

    int x_coOrd;
    int y_coOrd;
    ship* nextShip;

};

ship* p_enemies = NULL;


ship* getNewShip(){


     ship* p_ship = new ship;
     p_ship->x_coOrd = 0;
     p_ship->y_coOrd = 0;
     p_ship->nextShip = p_enemies;
     p_enemies = p_ship;
     return p_ship;

}



int main()
{
   ship* one = getNewShip();


}
  
Last edited on
A pointer to a pointer is rarly used. There are usually two scenarios:

1. You want to modify a pointer itself.
2. A 2-dimensional array.

whats the point of pointers to pointers like this **p?
For instance:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
node *root; // This is the root of a list
void clear_list(node **p)
{
  delete *p; // Note that this delets the object pointed to due to the dereference operator *
  *p = NULL; // Note this sets the pointer to null
}
...
int main()
{
  root = new node;

  // Do something with root...

  clear_list(&root); // Now the list will be deleted and after the function returns the root pointer is set to NULL (note the reference operator & which provides the pointer to pointer)

  return 0;
}
Topic archived. No new replies allowed.