Question

Depending on a variable, I need to select the SeedPositions32 or SeedPositions16 array for further use. I thought a pointer would allow this but I can't seed to make it work. How do you declare a pointer to a C++11 std::array? I tried the below.

array<int>* ArrayPointer;
//array<typedef T, size_t Size>* ArrayPointer;
array<int,32> SeedPositions32 = {0,127,95,32,64,96,31,63,16,112,79,48,15,111,80,
                               47,41,72,8,119,23,104,55,87,71,39,24,7,56,88,103,120};
array<int,16> SeedPositions16 = {...}
Was it helpful?

Solution

std::array has a template parameter for size. Two std::array template instantiations with different sizes are different types. So you cannot have a pointer that can point to arrays of different sizes (barring void* trickery, which opens its own can of worms.)

You could use templates for the client code, or use std::vector<int> instead.

For example:

template <std::size_t N>
void do_stuff_with_array(std::array<int, N> the_array)
{
  // do stuff with the_array.
}

do_stuff_with_array(SeedPositions32);
do_stuff_with_array(SeedPositions16);

Note that you can also get a pointer to the data:

int* ArrayPtr =  SeedPositions32.data();

but here, you have lose the size information. You will have to keep track of it independently.

OTHER TIPS

You can simply access the content of the std::array as a raw C-like array pointer using the std::array::data() member function:

int* arrayPointer = useSeedPositions32 ? SeedPositions32.data() : SeedPositions16.data();

In his answer juanchopanza explained very well why what you want cannot work.

The question is why would you want to do that? There is no way where you could use a (pointer to) std::array<int,32> in place of std::array<int,16>.

The point of std::array<> is to keep track of the number of elements at compile time (and also to avoid memory allocation for small fixed-sized arrays). If you instead want the number of elements to be managed at run time, you should presumably not use std::array<>, but std::vector.

The alternative of obtaining a pointer to the underlying data (using std::array::data() as proposed in other answers) and keeping track of the number of elements by yourself is somewhat dangerous and not really recommendable. The problem is that you must ensure that the pointer is never dangling.

Finally, I cannot find any possible use case. In order to use your pointer, you must declare both an array<int,32> and an array<int,16> object, yet use only one of them. Why don't you simply only declare a array<int,32> and use only its first 16 elements if not all 32 are needed?

You could do something like this:

int * myArray = use32 ? &SeedPositions32[0] : &SeedPositions16[0];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top