How to pass a 2d tiles image to a function in C++

There are ways, but they have limitations.

Technically a 2D array is an array of arrays, so you can’t have a pointer to a 2D array without specifiying the size of its 2nd dimension.

E.g.

int a[2][3];
int (*p)[3] = a;

You could maintain a class that had a pointer to each row of the array, but then you’d either need dynamic allocation or you’d still need to know the size of the first dimension.

If all your 2D arrays are the same size then you can get away with something like:

class LookupTable
{
private:
	const int (*lookup)[2][3];
public:
	LookupTable(const int (&lookup)[2][3])	: lookup(&lookup) {}
};

If you need the class to be independent of the width and height of the array then it might be best to use a ‘flat array’ - a 1D array pretending to be a 2D array.

class MemoryArray
{
private:
	const int * array;
	std::size_t width;
	std::size_t height;

	std::size_t getIndex(std::size_t x, std::size_t y) const
	{
		return (y * width) + x;
	}

public:
	template< std::size_t size >
	MemoryArray(const int(&array)[size], std::size_t width, std::size_t height)
		: array(array), width(width), height(height)
	{
		if (width * height > size)
			/*ERROR*/;
	}

	int get(std::size_t x, std::size_t y) const
	{
		return this->array[this->getIndex(x, y)];
	}
};
2 Likes

Flat arrays really are best if I can throw a recommendation here. You deal with them the same way as 1D arrays, the whole prize is keeping in mind that simple indexing formula

i = y * width + x

That’s it.

Going down the ‘true’ 2D arrays just leads you down the road of pointers to pointers, weird argument passing, cycles of malloc/free etc. Not good.

2 Likes