简体   繁体   English

如何返回指向我的二维数组的指针? C++

[英]How can i return a pointer to my 2d array? C++

The following is declared as global variable in a class:以下在类中被声明为全局变量:

int mazeLayout[MAZEHEIGHT][MAZEWIDTH]
    ={{1,1,1,1},
      {1,0,0,0}};

Then i have a public function that I want to return a pointer to the array called from another function in another class/header file:然后我有一个公共函数,我想返回一个指向从另一个类/头文件中的另一个函数调用的数组的指针:

int *getMazeLayout(){return *mazeLayout};

I get an error in here "expected ';'我在这里收到一个错误“预期的';' before '}' token"在 '}' 标记之前”

There are many little corner cases here.这里有很多小角落案例。

First a 2D int array is not an int ** - the latter should be an array of pointers pointing to the individual rows of the 2D array.首先,二维 int 数组不是int ** - 后者应该是指向二维数组各行的指针数组。 They are used the same but are not same animal.它们使用相同但不是同一种动物。

Here you could do:在这里你可以这样做:

int mazeLayout[MAZEHEIGHT][MAZEWIDTH]
    ={{1,1,1,1},
      {1,0,0,0}};
int *pMazeLayout[] = { mazeLayout[0], mazeLayout[1] };

int **getMazeLayout(){return pMazeLayout;}   // ; before }

But as you wanted to return a pointer to the 2D array, the exact way would be:但是当你想返回一个指向二维数组的指针时,确切的方法是:

typedef int MAZE[MAZEHEIGHT][MAZEWIDTH];

MAZE *getMazeLayout() {
    return &mazeLayout;
}

You can then use:然后您可以使用:

MAZE *layout = getMazeLayout();
int val = (*layout)[1][2];

But it gives you an additional indirection level.但它为您提供了一个额外的间接级别。

Alternatively you could just return a pointer to first row:或者,您可以只返回一个指向第一行的指针:

typedef int ROW[MAZEWIDTH];

ROW *getMazeLayout() {
    return mazeLayout;
}

You can then use:然后您可以使用:

ROW *layout = getMazeLayout();
int val = layout[1][2];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM