Matthew Matthew - 3 months ago 12
C++ Question

C++ - Creating pointers to elements of an array containing pointers to class objects

I'm new to C++ and programming in general and am trying to learn by creating a sort of game as I go along. I can't find any information on how to achieve what I need to do.
I have created the following code, which I believe creates new objects of class Player off the heap, and creates pointers to these objects in an array.

int playerObjects(int n, int gameMode)
{
Player* playerArray = new Player[n];
for (int i = 0; i < n; i++)
{
playerArray[i].balance = 50;
playerArray[i].score = 0;
playerArray[i].playerNum = (i+1);
int m = (i+1);
playerArray[i].playerName = playerArray[i].playerN(m);
string playerNam = playerArray[i].playerName;
playerArray[i].playerAge = playerArray[i].playerA(playerNam);
playerArray[i].teamNum = 0;
}
}


where n is the number of players (from 1-4).
The class
Player
I have created myself:
What I now want to do is return to the calling function, main(), and still be able to access and modify these objects. I cannot figure out how. I have attempted to create pointers to each element of the array, like so:

Player** pOne = playerArray[0];
Player** pTwo = playerArray[1];
Player** pThree = playerArray[2];
player** pFour = playerArray[3];


which I think declares pOne to be a pointer to a pointer to an object of class Player (the array element), however, this throws the error:
cannot convert 'Player' to 'Player**' in initialization


doing it like this throws the same error, but in assignment rather than initialization (obviously):

Player** pOne;
pOne = playerArray[0];


How do I do it?
And, once I have done it, how do I then pass this from main() to other functions that also need to have access to these?
Would it be better to declare the array globally?

Thanks

Answer

The easiest way is probably to just return the pointer.

Player* playerObjects(int n, int gameMode)
{
    Player* playerArray = new Player[n];
    ...
    return playerArray;
}

Alternatively if you want to keep the return value as an int, you can pass a pointer to a pointer to the function. You can then create the array in the specified pointer.

int playerObjects(int n, int gameMode, Player** playerArray)
{
    *playerArray = new Player[n];
    for (int i = 0; i < n; i++)
    {
        *playerArray[i].balance = 50;
        *playerArray[i].score = 0;
    ...
    }
}

You can call this function by doing:

Player* playerArray;
playerObjects(n, gameMode, &playerArray)

And then access the items of playerArray as usual:

playerArray[0].xyz;

Don't forget that after you've allocated memory with with new[], you need to delete it with delete[] when you're finished with it.