code_by_cr
code_by_cr

Reputation: 23

How can I write a method that receives, processes and returns a 2D char array in C++

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)

Upvotes: 1

Views: 96

Answers (1)

Nikos Athanasiou
Nikos Athanasiou

Reputation: 31577

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

Upvotes: 2

Related Questions