I have a class with a matrix that calls another function and passes it there

class A { int field[20][10]; public: void method() { func((/*Здесь сделать преобразование*/)field); } }; 

but the function takes the type int (*) []. I need to do the conversion in brackets but I don’t know how to write

  • func ((int **) field); //not? - asianirish
  • @asianirish not - Hujuk
  • The function should not accept int (*)[] , it is impossible to convert int [20][10] to this type, and int [] is incomplete. Use std::array or some class of matrices. - VTT
  • For two-dimensional arrays, in my opinion, it always worked like this: func(int** array){}; funct(field); func(int** array){}; funct(field); - nick_n_a
  • @nick_n_a, it never worked for two-dimensional arrays. Read here , I described the difference there. - ixSci

2 answers 2

Ambiguities are due to the fact that the pointer and the array are all different types. Therefore, the cast here is not suitable. Pointer to pointer and array of pointers, respectively, also different types. Need to change the func function.

In your case the following solutions are possible:

1. Function for a specific array (suitable if you have a function that only works with arrays of a certain and previously known size)

 void func(int matrix[][10]); 

2. Generalized pattern

 template <size_t Size> void func(int matrix[][Size]); 

But still, if you write in C ++, it is better to use the tools from the standard library. std::array almost as good as built-in arrays.

  • Still, the dimension of the first bracket will have to be passed to the function so that you can work with it. It is impossible to work with matrix in this form - ixSci
  • @ixSci, I agree. and pass a separate argument, because foo(int matrix[20][10]) can accept and int a[50][10] and, more sadly, int a[5][10] - acade
  • Yeah, the older part turns into a pointer. This can be bypassed like this: template<size_t N, size_t M> void foo(int (&matrix)[M][N]) - ixSci
  • It’s not clear where the "pointer and array are all different types". The original array is of type int [20][10] and is easily converted to the pointer int (*)[10] . The author of the question needs (for some reason) to get an int (*)[] . This reinterpret_cast pointer -> pointer. Besides the fact that this is a reinterpret_cast , there is nothing wrong with it. - AnT 1:54 pm

The literal answer to your question is:

 class A { int field[20][10]; public: void method() { func((int (*)[]) field); } }; 

That is, right here in brackets and write. (Therefore, it is not clear that you have caused difficulties here.)

And what the func function will do next with this type is not clear from your question. Formally, all she can do is convert it back to the “correct” type.