1

normally I'm a Java guy and I'm trying to write a method that receives, processes and returns a 2D char array in C++.

I tried this:

char[][] updateMatrix(char (&matrix)[3][3])
{
 matrix [1][2] = 'x';

 return matrix
}

int main() 
{
 char matrix[3][3] = {   {1,2,3},
                         {4,5,6},
                         {7,8,9} };

 matrix = updateMatrix(matrix);
}

but I'm not sure if it´s the "right" way to hand over this 2D Array and how I can return it to override the current matrix. (casting solutions are also welcome)

code_by_cr
  • 21
  • 6
  • The short answer is you don't. Wrap your 2D array into a class and return an object of that type. – sweenish Nov 02 '21 at 20:38
  • 1
    2D arrays are an absolute to pass around in C++. The usual recommendation is you use a smarter container such as a `std::vector` or `std::array` – user4581301 Nov 02 '21 at 20:39
  • Also consider using Eigen if you intend to use actual linear algebra in your C++ program, both for performance and simplicity: https://eigen.tuxfamily.org/dox/GettingStarted.html – m88 Nov 02 '21 at 20:41
  • 1
    Side note: If you pass in an array, it will be passed by reference. Since you can directly manipulate the source array, there's not much point to returning it. – user4581301 Nov 02 '21 at 20:41
  • In C++, if you get parameter by reference, you can just modify it, and make function void – Shadasviar Nov 02 '21 at 20:44
  • 1
    For your array initialization: `3` is an integer (which can be converted to a char, but I don't think that's what you expect). Perhaps you want`'3'` which is a char. – Ripi2 Nov 02 '21 at 20:44
  • Read [this SO question](https://stackoverflow.com/questions/8767166/passing-a-2d-array-to-a-c-function) – Ripi2 Nov 02 '21 at 20:45

1 Answers1

2

The syntax to return a reference to an array is a bit funky in C++. Long story short the signature of your function should look like this:

char (&updateMatrix(char (&matrix)[3][3]))[3][3];

Demo

The reason why you'll hardly ever see this written in C++ is because when you pass something by reference, you don't need to return it; instead you'd simply modify it in place (it will be an in/out parameter).

A case where such a thing is useful is when you need to chain operations, and you prefer the resulting syntax e.g. inverse(transpose(matrix)). If you go with returning the (reference to the) array, it's always simpler to create a typedef and remove some of the clutter:

using mat3x3 = char[3][3];

mat3x3& updateMatrix(mat3x3& matrix)
{
    matrix [1][2] = 'x';

    return matrix;
}

Demo

Nikos Athanasiou
  • 29,616
  • 15
  • 87
  • 153
  • Many thanks for your fast answer now it´s simply logical, you helped me a lot. – code_by_cr Nov 03 '21 at 19:46
  • @cr_nasty No worries, declarations in C++ can become difficult to understand. I like this utility a lot https://cdecl.org/ which translates from C to english or vice versa – Nikos Athanasiou Nov 03 '21 at 21:46