string 2d array

i have a function that contain a 2d string array & i need to return the whole array to the main function,but i found that the ordinary return fails, how can i do this?
Last edited on
I dont know what you mean by "the ordinary return fails", there is no reason why it should fail. Though it might be inefficient to return a double dimension array from a function.

Good start will be to read http://www.cplusplus.com/doc/tutorial/functions/ especially the pass by reference section.

its an assignment, i have to return the 2d string, and use its value inside main function ,but when i recall it it show me error that the array is not declared in the main function.
As codewalker said use reference to an array or a pointer, as returning whole array is problematic.
Last edited on
It isn't just problematic -- you cannot return an array from any function. (An array is not a first class object in C and C++.)

There are two ways to handle it.

(1) Pass the result array as argument:

1
2
3
4
5
6
void set_identity_matrix( double m[ 4 ][ 4 ] )
{
  for (unsigned r = 0; r < 4; r++)
  for (unsigned c = 0; c < 4; c++)
    m[ r ][ c ] = (double)(r == c);
}
1
2
3
4
5
6
int main()
{
  double my_matrix[ 4 ][ 4 ];

  set_identity_matrix( my_matrix );

(2) Dynamically allocate the array:

 
typedef matrix_t[ 4 ][ 4 ];
1
2
3
4
5
6
7
8
matrix_t* allocate_identity_matrix()
{
  matrix_t* m = new matrix_t;
  for (unsigned r = 0; r < 4; r++)
  for (unsigned c = 0; c < 4; c++)
    m[ r ][ c ] = (double)(r == c);
  return m;
}
1
2
3
4
5
6
7
int main()
{
  matrix_t* my_matrix = allocate_identity_matrix();

  ...

  delete [] my_matrix;

If you think that all looks kind of messy -- encapsulate it in a class, much like std::vector or std::array.

1
2
3
4
5
6
7
8
9
10
11
12
13
class matrix_t
{
  double data[ 4 ][ 4 ];
  ...
};

matrix_t identity_matrix()
{
  matrix_t m;
  for (...)
    ...
  return m;
}
1
2
3
4
5
int main()
{
  matrix_t my_matrix = identity_matrix();

  ...


Hope this helps.
thanks Duoas,thanks all replier
Topic archived. No new replies allowed.