Piotr Müller
Piotr Müller

Reputation: 5548

How to cast pointers-represented 2D array back to 2D array in C++?

I have a variable in class declared as compile-time constant with known size:

static const int array[5][5]; // constants initlialised in another place

And a function that returns it virtually:

virtual const int** getArray() { return array; }

How to get this array with this method, and cast it to fixed-size array, not pointers-based, so I can use it like cout << data[2][2] ?

Sample that dosn't compile:

const int[5][5] data = object->getArray();
cout << data[2][2]; 

Sample that compiles but crashes application:

const int** data = object->getArray();
cout << data[2][2]; 

Note: one solution is to create typedef arr[5] and declare methods with arr* but i don't want to create a typedef for each compile-time size wich I use like typedef arr5[5]; typedef arr10[10] etc. I'm looking for something more like:

const int(*)[5] data = object->getArray(); // won't compile, example only

Let's assume that compile-time constant array is loaded with dynamic DLL and is already in memory, is it possible to use this data as array without allocating new memory and populating it from compile-time constants?

Upvotes: 0

Views: 713

Answers (4)

john
john

Reputation: 8027

It's simple enough, you are almost there

const int(*)[5] data = reinterpret_cast<int(*)[5]>(object->getArray());

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254471

virtual const int** getArray() { return array; }

That won't work, and shouldn't compile; you're trying to return a pointer to some pointers, but there are no pointers to point to, only an array of arrays.

You can return a pointer to those arrays, preserving the type:

virtual const int (*getArray())[5] { return array; }
const int (*data)[5] = getArray();
cout << data[2][2];

In C++11, it might be nicer to wrap the arrays up in std::array, and return a reference to that, to avoid some of the nasty syntax.

Upvotes: 2

juanchopanza
juanchopanza

Reputation: 227418

Use std::array:

#include <array>

static const std::array<std::array<int, 5>, 5> myarray; // constants initlialised in another place

virtual const std::array<std::array<int, 5>, 5>& getArray() const 
{ 
  return myarray; 
}

If you do not have C++11 support, you can use std::tr1::array or boost::array (or roll out your own fixed size array type.)

Upvotes: 1

Serve Laurijssen
Serve Laurijssen

Reputation: 9733

that is not possible. You lose all size information when an array is passed to or returned from a function. The array decays into a pointer so to speak

Upvotes: 0

Related Questions