Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ alignment of multidimensional array structure

In my code, I have to consider an array of arrays, where the inner arrays are of a fixed dimension. In order to make use of STL algorithms, it is useful to actually store the data as array of arrays, but I also need to pass that data to a C library, which takes a flattened C-style array.

It would be great to be able to convert (i.e. flatten) the multi-dimensional array cheaply and in a portable way. I will stick to a very simple case, the real problem is more general.

struct my_inner_array { int data[3]; };
std::vector<my_inner_array> x(15);

Is

&(x[0].data[0])

a pointer to a continuous block of memory of size 45*sizeof(int) containing the same entries as x? Or do I have to worry about alignment? I am afraid that this will work for me (at least for certain data types and inner array sizes) but that it is not portable.

  1. Is this code portable?
  2. If not, is there a way to make it work?
  3. If not, do you have any suggestions what I could do?
  4. Does it change anything at all if my_inner_array is not a POD struct, but contains some methods (as long as the class does not contain any virtual methods)?
like image 348
Markus Mayr Avatar asked Nov 05 '22 02:11

Markus Mayr


1 Answers

1 Theoretically no. The compiler may decide to add padding to my_inner_array. In practice, I don't see a reason why the compiler would add padding to a struct that has an array in it. In such a case there's no alignment problem creating an array of such structs. You can use a compile time assert:

typedef int my_inner_array_array[3];
BOOST_STATIC_ASSERT(sizeof(my_inner_array) == sizeof(my_inner_array_array));

4 If there are no virtual methods it shouldn't make any difference.

like image 147
selalerer Avatar answered Nov 09 '22 04:11

selalerer