Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you declare a pointer to a C++11 std::array?

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 = {...}
like image 941
whitebloodcell Avatar asked Apr 09 '14 08:04

whitebloodcell


People also ask

How do you declare a pointer to an array of pointers?

To declare a pointer to an array type, you must use parentheses, as the following example illustrates: int (* arrPtr)[10] = NULL; // A pointer to an array of // ten elements with type int. Without the parentheses, the declaration int * arrPtr[10]; would define arrPtr as an array of 10 pointers to int.

How do you declare a pointer in C++?

The syntax simply requires the unary operator (*) for each level of indirection while declaring the pointer. char a; char *b; char ** c; a = 'g'; b = &a; c = &b; Here b points to a char that stores 'g' and c points to the pointer b. This is a special type of pointer available in C++ which represents absence of type.

Is std :: array a pointer?

std::array::dataReturns a pointer to the first element in the array object. Because elements in the array are stored in contiguous storage locations, the pointer retrieved can be offset to access any element in the array.


1 Answers

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.

like image 195
juanchopanza Avatar answered Sep 20 '22 20:09

juanchopanza