我是一名Java程序员,我正在为这个简单的问题苦苦挣扎。
如何返回这个多维数组?它必须返回一个指针吗?我该如何在另一个文件中获取它?
static MoveDirection ghost_moves[GHOSTS_SIZE][4];
MoveDirection** get_ghost_moves() {
return ghost_moves;
}
get_ghost_moves
的正确声明应该是声明它返回一个指向数组的指针:
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;
}
这个语法非常令人困惑,因此我建议为其创建一个typedef:
// Define MoveDirectionArray4 to be an alias for "array of 4 MoveDirections"
typedef MoveDirection MoveDirectionArray4[4];
MoveDirectionArray4 *get_ghost_moves() {
return ghost_moves;
}
#define MAX 20
char canopy[20][MAX];
typedef char frank[MAX];
frank friend[MAX];
frank *getList()
{
return friend;
}
void test(int n)
{
frank *list = getList();
int i;
for (i = 0; i < 5; i++ )
{
printf("list[%d] %s\n\r", i, list[i]);
}
}
int main(void)
{
int i, nf;
for (i = 0; i < 5; i++ )
{
snprintf(friend[i], MAX, "test%d", i);
printf("test[%d] %s \n\r", i, friend[i]);
}
test(5);
return 0;
}
ghost_moves
占据了一段连续的 GHOSTS_SIZE*4
个 MoveDirections 的内存空间:它相当于一个 MoveDirection*
它不能与指向指针的指针一起使用,而是需要单独使用一个指针。
如果你想使用两个operator[]
来索引你的数组,你有两个选择:
使用类型为MoveDirection (*ghost_moves) [GHOST_SIZE]
的变量,然后只需执行ghost_moves[i][j]
这主要是为了拥有指向指针的指针,通常不是一个好的解决方案:将ghost_moves
的类型设置为MoveDirection**
例如:
MoveDirection ghost_moves_original[GHOST_SIZE][4];
MoveDirection *ghost_moves[GHOST_SIZE];
ghost_moves[0] = ghost_moves_original;
ghost_moves[1] = ghost_moves_original + GHOST_SIZE;
...
GHOSTS_SIZE*4*sizeof(MoveDirection)
:) - Billy ONeal多维数组不是指针数组。它是一个单一的内存块。它只在声明它的作用域内有意义。
你不能像这样干净地返回它.. 你必须返回一个 MoveDirection[GHOSTS_SIZE][4]
。