another pointer question

Hi guys I'm getting the hang of pointers thanks to all the great people on this forum =) but I have one question here is my sample code

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
41
42
 #include <iostream>

using namespace std;


struct spaceShip{

    int position;
    int weaponPower;
    int* nextEnemy;

};

spaceShip* getNewEnemy(){

     spaceShip* p_ship = new spaceShip;
     p_ship->position = 0;
     p_ship->weaponPower = 20;
     p_ship->nextEnemy = NULL;

     return p_ship;
}

void upgradeWeapons(spaceShip* s){

      (*s).weaponPower += 30;

}


int main()
{
    spaceShip one;
    spaceShip* pointer;
    pointer = &one;

    one.weaponPower = 20;
    upgradeWeapons(pointer);

    cout << one.weaponPower << endl;
}


anyway what is the difference between passing a pointer into a function which has a pointer as the parameters like upgradeWeapons and passing a memory address into the same function both seem to work fine and I get the same result but I thought when I passed in a memory address I might get an error so how come this is legal and what is the difference?

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15


int main()
{
    spaceShip one;
    spaceShip* pointer;
    pointer = &one;

    one.weaponPower = 20;
    upgradeWeapons(pointer); // LEGAL

    cout << one.weaponPower << endl;
}



and

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16


int main()
{
    spaceShip one;
    spaceShip* pointer;
    pointer = &one;

    one.weaponPower = 20;
    upgradeWeapons(&one); // ALSO LEGAL

    cout << one.weaponPower << endl;
}





Thanks
Last edited on
There is no difference. &one gives you a pointer to one.
Note that you could avoid pointers by using reference parameters:
1
2
3
void upgradeWeapons( spaceShip & s ){
      s.weaponPower += 30;
}


With the pointer version this is syntactically legal:
1
2
3
4
int main()
{
  upgradeWeapons( nullptr );
}

If it is legal, is it logically correct too?
anyway what is the difference between passing a pointer into a function which has a pointer as the parameters like upgradeWeapons and passing a memory address into the same function both seem to work fine and I get the same result but I thought when I passed in a memory address I might get an error so how come this is legal and what is the difference?

There is no difference. A pointer is a memory address. More specifically, a pointer is an integer, and the value of that integer is a memory address.

When you pass a pointer into a function, you are passing in a memory address.
Last edited on
Topic archived. No new replies allowed.