Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a pointer of a multidimensional array

Tags:

c

pointers

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;
}
like image 383
David Robles Avatar asked Dec 13 '22 17:12

David Robles


1 Answers

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;
}
like image 77
Adam Rosenfield Avatar answered Dec 15 '22 07:12

Adam Rosenfield