简体   繁体   中英

C++ pointer to 2D array

Hi I know there are a lot of similar questions but I've been through them and I can't seem to make my function work. I need to return a pointer to a 2D array. So far I am using this code:

(This code is a function in Level.cpp)

TileType* CLevel::getTiles()
{
TileType (*matrix_ptr)[31] = tiles;

return *matrix_ptr;
 } 

(TileType is an enum) This function is just returning one row and I obviously need both. Any suggestions?

Header file Level.h:

class CLevel 
{
private:

list<CBox> boxes;
TileType tiles[GRID_HEIGHT][GRID_WIDTH];
CPlayer player;

public:
CLevel();
~CLevel();

CPlayer* getPlayer();
list<CBox>* getBoxes();
TileType** getTiles();
};

Don't define getTiles().

You are completely breaking the encapsulation of the class. This doesn't always matter but in this case the C/C++ 2D array is not a fit structure for passing outside where its dimensions might not be known.

So define your operations on tiles as methods of CLevel.

What you should do is either this:

// Class declaration
class CLevel
{
public:
   TileType (*getTiles())[GRID_WIDTH];

   TileType tiles[GRID_HEIGHT][GRID_WIDTH];

   //...
};

// Implementation
TileType (*CLevel::getTiles())[GRID_WIDTH]
{
   return tiles;
}

or this:

// Class declaration
class CLevel
{
public:
   TileType (&getTiles())[GRID_WIDTH][GRID_HEIGHT];

   TileType tiles[GRID_HEIGHT][GRID_WIDTH];

   //...
};

// Implementation
TileType (&CLevel::getTiles())[GRID_WIDTH][GRID_HEIGHT]
{
   return tiles;
}

It's a bit of a complicated declaration but read it inside out: in both cases getTiles() is a function that returns a reference to a 2D array of tiles (the example shows two forms of syntax). By calling getTiles() you're actually referring to tiles . You can even call the function it in this way: getTiles()[i][j] .

If you want to return a pointer to a 2d array, then your function declaration should be:

TileType** CLevel::getTiles()

And your return should be matrix_ptr, not its pointer content (which is a one-dimension array).

return matrix_ptr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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