I'm Java programmer and I'm struggling with this simple stuff.
How can I return this multidimensional array? Does it have to return a ** pointer? How can I get it in another file?
static MoveDirection ghost_moves[GHOSTS_SIZE][4];
MoveDirection** get_ghost_moves() {
return ghost_moves;
}
A 2D array is not a pointer to a pointer. Arrays and pointers are fundamentally different types in C and C++. An array decays into a pointer to its first element (hence the frequent confusion between the two), but it only decays at the first level: if you have a multidimensional array, it decays into a pointer to an array, not a pointer to a pointer.
The proper declaration of get_ghost_moves
is to declare it as returning a pointer to an array:
static MoveDirection ghost_moves[GHOSTS_SIZE][4];
// Define get_ghost_moves to be a function returning "pointer to array 4 of MoveDirection"
MoveDirection (*get_ghost_moves())[4] {
return ghost_moves;
}
This syntax syntax is extremely confusing, so I recommend making a typedef for it:
// Define MoveDirectionArray4 to be an alias for "array of 4 MoveDirections"
typedef MoveDirection MoveDirectionArray4[4];
MoveDirectionArray4 *get_ghost_moves() {
return ghost_moves;
}
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