I should know this, but unfortunately I don't...
I have an array in a file called Character.h that looks like the following:
char board[8][8];
And I want a function that returns this array called Get_Player_Board(), but I do not for the life of me know how to return this array! I have tried eveything I know and still cant get it to return...someone help me![?]
I have declared the function in a source file and it is declared as follows:
char Character::Get_Player_Board()
{
//need to return array here
}//close function
You can either return a pointer to the array, or pass in a pointer to a pointer of the array of that size as a function parameter, then the function sets the pointer.
i.e.
[code]
char board[][];
void Get_Player_Board( char ** b ) { *b = board; }
[/code]
Either that or you could make the board be a structure instead of a character, although you'd still have a similar problem. Unless you wrapped the whole board in a structure or class, but that's going OO, and I don't think that you are doing that atm.
ok, i tried what you said Daemin, and it spat out this error
my new code looks like
[code]
void Character::Get_Player_Board(char **tempBoard)
{
*tempBoard = playerBoard;
} //close Get_Player_Board function
C:KoolGame DevChessCharacter.cpp(60) : error C2440: '=' : cannot convert from 'char [8][8]' to 'char *'[/code]
What the?
Man, those smilies are making garbage of this thread :P
Ok, I think this comes down to the way the compiler (and ANSI standard too i guess!) percieves pointers and arrays as different entities. For instance, when you do
char c[10];
char *d;
d = c; // Note may need to be "d = &c"!
sizeof(c); // 10
sizeof(d); // 4 (sizeof(char*))
Because of this, often you can't directly assign an array to a pointer, and sometimes if you can strange things may occur that you don't expect...
The solution to this should simply be to replace:
*tempBoard = playerBoard;
with
*tempBoard = &playerBoard;
or, i like to use this for better (IMO) readability
*tempBoard = &(playerBoard[0][0]);
This just takes the address of the array (first element of the array).
AFAIK the array and the array address should both equate to the same pointer value, but the compiler just throws a fit over type differences. Hope i'm not wrong :)
Hope that helps.
CYer, Blitz
You can pass the whole array by reference like this (remember, a 2d array is basically just a pointer
to a pointer (in c++)):
char ** Get_Player_Board()
{
char **board; // Your board array
return board;
}
or you can pass in the pointer and set it to that value as mentioned earlier
void Get_Player_Board(char **b)
{
char **board; // your board array
b = board;
}
um i didnt think you could return an array.
but u cant return a pointer to the array. well thats what ive been doing anyway :)