简体   繁体   中英

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)

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 eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM