What is happening on this line? * & ->

copied this from github. This line is confusing me. What is the meaning of the left side? Is it creating a global const variable called Player?

On the right side I'm also a bit lost. I haven't used arrows or deference pointers before


 
  const Player *player = &state->players[dot->team];


Function i took this out of

1
2
3
4
5
6
7
void Move::stepDots() {
    for(int i = 0; i < NUMBER_OF_TEAMS*state->dotsPerTeam; i++) {
        Dot* dot = state->dots[i];
        const Player* player = &state->players[dot->team];
        moveDotToward(dot, player);
    }
}


And here is part of state.hpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class State {
    public:
        int me;
        bool currentlyDrawing;
        float timeSidebar;
        int displayWidth;
        int displayHeight;
        Player players[NUMBER_OF_TEAMS];
        Map* map;
        std::vector<Dot*> dots;
        Dot* field[WIDTH][HEIGHT];
        std::vector<float> points;
        std::vector<float> colours;
        Random* moveRandom;
        Random* aiRandom;
        int dotsPerTeam;
        State(int team, int mapId, int seed, int dotsPerTeam);
        ~State();
        void placeTeams();
};


My programming experience is pretty much only lua. I've barely touched c++ until a week ago.
Last edited on
Hi

I've barely touched c++ until a week ago.


Perhaps you should start with something easier.

What is the meaning of the left side?


Read from right to left:

const Player *player

The variable player is a pointer to type Player which is const.

I prefer to put the * next to the type, because C++ is all about types:

const Player* player

The variable player is a local variable because the declaration is inside a function.

On the right side I'm also a bit lost. I haven't used arrows or deference pointers before


= &state->players[dot->team];

The ampersand means take the address of the variable state. The -> in this context means dereference pointer to member. &state->players obtains the players array. players is an array of pointers, and dot->team obtains the subscript value team from the pointer dot

Good Luck !!



The ampersand takes the address of the result of the expression state->players[dot->team] -- that is, the expression obtains the address of the element at offset dot->team in the array.

It could also be written (more nicely, IMO) without the ampersand as state->players + dot->team;
Last edited on
Topic archived. No new replies allowed.