[Solved] 1D array passed to function as 2D array


template<size_t stride, class T, size_t N, size_t count = N/stride>
std::array<T*, count> make_2d( T(&raw)[N] ) {
  std::array<T*, count> retval;
  for (size_t i = 0; i < count; ++i)
    retval[i] = raw + i*stride;
  return retval;
}

this will return a array of pointers to the lower dimensions

To call func2, simply do:

func2( 10, make_2d<10>(arr).data() );

this assumes that the number of samples is fixed, and that you want an array of pointers to each of the samples.

The above does it with no dynamic allocation.

Note that arr must be of type double arr[60] for the above to work. float64 is hopefully an alias to a double. If arr is a function parameter, even if it has the number 60, it isn’t really a double arr[60], but “really” a double*.

This can be gotten around with a bit of creative casting:

using parr_t = double(*)[60];
func2( 10, make_2d<10>(*(parr_t)(arr)).data() );

if the same array (at the same location in memory) is being repopulated with samples repeatedly, you can do the make_2d call once, and use it each time.

4

solved 1D array passed to function as 2D array