0

For example, if i have a function defined as:

double** trans(double **A)

and a matrix defined as

double A[3][3]={1,1,1,1,1,1,1,1,1};

How can I use this matrix as a input for the function?

user4581301
  • 33,082
  • 7
  • 33
  • 54
Michael
  • 17
  • 2
  • You cannot. An array will [decay to a pointer](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay), but in this case, it won't decay to a pointer to a pointer, it will decay to a pointer to an array of 3 elements. Recommendation: Arrays are really simple and difficult to pass around correctly. Use `std::array` if you know the size of the array at compile time or a `std::vector` ([wrapped up to look like it is 2D](https://stackoverflow.com/a/2076668/4581301)) if you don't know the size when compiling. – user4581301 Sep 22 '21 at 17:33
  • C-style arrays are pretty easy to get wrong. There is no way to cast a `double[3][3]` to a `double**`, because **arrays are not pointers**. As commented, try C++ solutions like `std::vector` or `std::array`. – Drew Dormann Sep 22 '21 at 17:39
  • Thanks for the answer. As a beginner, what I am trying to do is create a function, and do different operations depending on the dimension of the input matrix. The only way that I know to make it work is using the input as a double pointer, however, as you said, the way I defined the matrix is a pointer to three arrays. Is there a way to solve this? – Michael Sep 22 '21 at 17:40
  • If the dimensions of the matrix are important, you will lose that information with `double**`. Consider the alternatives that were suggested. Pointers to pointers are usually a code smell in beginner C++ code. – Drew Dormann Sep 22 '21 at 18:41
  • You can't. The conversion between an array and a pointer (to its first element) (aka the "equivalence" of arrays and pointers) only works in one dimension AND only in some specific circumstances. A two-dimensional array is an array-of-one-dimensional-arrays, so can be converted to a pointer-to-a-one-dimensional-array. It can NOT be converted to a pointer-to-a-pointer (forcing the conversion generally means the subsequent dereferencing or double-dereferencing of the pointer gives undefined behaviour). – Peter Sep 22 '21 at 21:31

0 Answers0