How to return two-dimensional arrays in C ++

I am trying to implement the Matrix4x4 class for my 3D Engine port, which I did earlier. Here is what I have in my header file:

#ifndef MAT4_H #define MAT4_H class Matrix4 { public: Matrix4() {} float[4][4] getMatrix() { return m; } //... //other matrix related methods are omitted //... private: float m[4][4]; }; #endif 

But the method that should return a two-dimensional array causes this error:

 src/Matrix4.h:13:10: error: expected unqualified-id before '[' token float[4][4] getMatrix() { return m; } ^ 

I apologize if this question already has an answer, but the answers I found on this site usually related to returning pointers instead of an array. Hope you can help, thanks.

+5
source share
3 answers

I would suggest using std::array . But using it directly in code, like a multi-array, is a little ugly. Therefore, I propose an alias that is defined as:

 #include <array> namespace details { template<typename T, std::size_t D, std::size_t ... Ds> struct make_multi_array : make_multi_array<typename make_multi_array<T,Ds...>::type, D> {}; template<typename T, std::size_t D> struct make_multi_array<T,D> { using type = std::array<T, D>; }; } template<typename T, std::size_t D, std::size_t ... Ds> using multi_array = typename details::make_multi_array<T,D,Ds...>::type; 

Then use it like:

 public: multi_array<float,4,4> getMatrix() { return m; } private: multi_array<float,4,4> m; 

You can use the alias in other places, for example:

  //same as std::array<int,10> //similar to int x[10] multi_array<int,10> x; //same as std::array<std::array<int,20>,10> //similar to int y[10][20] multi_array<int,10,20> y; //same as std::array<std::array<std::array<int,30>,20>,10> //similar to int z[10][20][30] multi_array<int,10,20,30> z; 

Hope this helps.

+9
source

Passing an array to C or C ++ is possible using a pointer to its first element - the pointer is passed by value.

The only way to pass an array by value is to encapsulate it in a structure, but in most cases it is better to pass a pointer and then copy all the data by value.

0
source

Just return the pointer to the first element of the array! :)

-1
source

Source: https://habr.com/ru/post/1204589/


All Articles