Here is my problematic coding: I have to take in 2 player's name. Then when for the next part when the player marker changes the name stored in "currentPlayer" should change too the name stored in either playerOne or playerTwo. It doesn't so how do I fix that? Please solve, I tried to make it a reference variable with the & symbol but I get an error saying array of reference is not allowed.
void boardMarker(int &, char playerOne[], char playerTwo[], char &playerMarker, char currentPlayer[]);
int main()
{
char playerOne[100];
char playerTwo[100];
char currentPlayer[100] = "playername";
boardMarker(playerTurn, playerOne, playerTwo, playerMarker, currentPlayer);
}
void boardMarker(int &playerTurn, char playerOne[100], char playerTwo[100], char &playerMarker, char currentPlayer[100])
{
// Set player markers
//Player 1 uses X and Player 2 uses O
if ( playerTurn == 1 )
{
playerMarker = 'X';
currentPlayer = playerOne;
}
else
{
playerMarker = 'O';
currentPlayer = playerTwo;
}
}
C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.
You can just pass arrays as function arguments with definition of their size. bool canReach(char board[ROWS][COLS], int i, int j); When the size is unknown, pointers are the way.
C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a pointer type.
char playerOne[100]
is identical to char* playerOne
char*
to another char*
does not copy the string, it copies the pointer.The correct way to do this:
currentPlayer = playerOne;
is this:
strcpy(currentPlayer, playerOne);
Or, better yet, since this is C++ and not C, use std::string
instead of char
arrays. std::string
will behave essentially how you expect.
You are copying array pointers instead of the values in them.
Read a C tutorial on arrays http://augustcouncil.com/~tgibson/tutorial/arr.html
You want currentPlayer
to be a pointer-to-characters, then swap it between the two players:
Your code, edited:
void boardMarker(int&, char playerOne[], char playerTwo[], char &playerMarker, char** pCurrentPlayer);
int main()
{
char playerOne[100];
char playerTwo[100];
char* currentPlayer = playerOne;
boardMarker(playerTurn, playerOne, playerTwo, playerMarker, ¤tPlayer);
}
void boardMarker(int &playerTurn, char playerOne[100], char playerTwo[100], char &playerMarker, char** pCurrentPlayer)
{
// Set player markers
//Player 1 uses X and Player 2 uses O
if ( playerTurn == 1 )
{
playerMarker = 'X';
*pCurrentPlayer = playerOne;
}
else
{
playerMarker = 'O';
*pCurrentPlayer = playerTwo;
}
}
Some comments on your code:
playerTurn
and playerMarker
are not
declared. (I'm pretending they are
global variables, not shown here).int&
in the prototype of boardMarker.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With