omegasbk
omegasbk

Reputation: 906

Typedef of 2d array of pointers

I am trying to define a type for my 2d array of pointers so I can reduce the mess in my code. I had triple pointers so I thought it looked bad. I managed to refactor the code using typedef, but it was more like trial and error. I would like to know what this actually means:

typedef SomeClass* (&grid8x8)[8][8];

And why this functions returns ok values:

grid8x8 SomeOtherClass::getGrid()
{
    return grid;
}

The syntax of the typedef in this case is what is confusing me.

Upvotes: 0

Views: 305

Answers (3)

MikeMB
MikeMB

Reputation: 21156

It is a reference ((&)) to a 8 by 8 array ([8][8]) of pointers (*) to integers (int). Start parsing inside the innermost parenthesis right to left, then to the right and finally to the left again. In contrast, a reference to a pointer to an 8 by 8 array of ints would look like this:

typedef int (*& RefToPtrToGrid)[2][2];

Personally, I find c++11 style more readable:

using RefTo8x8GridofPtr = int* (&) [8][8];

//or even better with std::array 
using Grid8x8 = std::array<std::array<int*,8>,8>&;

//or, more flexible:
template<size_t M,size_t N>
using Grid = std::array<std::array<int*,N>,M>&; //usage: Grid<8,8> myGrid;

Also, as @Will Briggs said, you probably don't want to make the reference part of the type:

using Grid8x8 = int* [8][8];
//... and so on

Upvotes: 0

badgerr
badgerr

Reputation: 7982

Here's a C++11 answer (question is tagged C++ after all)

You could use a std::array to store your grids instead of C arrays. Depending on your preference towards templates the syntax is somewhat straightforward.

#include <array>
typedef std::array<std::array<SomeClass*, 8>, 8> grid8x8;

Upvotes: 1

Topological Sort
Topological Sort

Reputation: 2787

The typedef means: grid8x8 is a reference to an 8x8 array of pointers to SomeClass.

The SomeOtherClass::getGrid function is, I'd imagine, returning a reference then to a member variable SomeOtherClass::grid.

I would do it this way instead:

typedef SomeClass* (grid8x8)[8][8];


const grid8x8& SomeOtherClass::getGrid()
{
    return grid;
}

That way, you can have a grid8x8 OR a reference to a grid8x8. A little more versatile, and you're less likely to forget you're using that reference at times when you shouldn't.`

Upvotes: 2

Related Questions