1

This sounds easy and I've seen questions about this being answered by using a vector instead but I can't do that in my case so asking for help...

What should be my function signature for return2dArray() if I want to do this? Please note that I cannot use a vector. It really has to be int[][]. Thanks!

int* return2dArray()
{
    static int a[2][2] = {{1, 2}, {4, 5}};
    return a;
}

int main()
{
    auto x = return2dArray();

    for (int y = 0; y < 3 ; y++)
    {
        std::cout << "y is = " << x[y] <<std::endl;    
    }    
}
kzaiwo
  • 1,558
  • 1
  • 16
  • 45
  • 1
    Possible duplicate of [Return a 2d array from a function](https://stackoverflow.com/questions/8617683/return-a-2d-array-from-a-function) –  Jun 25 '19 at 05:57

3 Answers3

3

If you are going to treat the returned pointer as though it points to a simple, 1D, array, I suggest using just that -- a 1D array.

// int* return2dArray()
int* return1dArray()
{
    static int a[4] = {1, 2, 4, 5};
    return a;
}

An improvement on that would be to use a std::array.

#include <iostream>
#include <array>

std::array<int, 4>& return1DArray()
{
   static std::array<int, 4> a = {1, 2, 4, 5};
   return a;
}

int main()
{
    auto x = return1dArray();

    for (size_t i = 0; i < x.size() ; i++)
    {
       std::cout << "x[" << i << "] is = " << x[i] << std::endl;    
    }

    // Iterate using the range-for loop.
    for ( auto e : x )
    {
       std::cout << "e is = " << e << std::endl;    
    }
}

std::array is preferable to built-in arrays since you get the size() member function at no additional run time penalty. You may also use begin() and end() functions if you want to iterate over the objects of the array.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

One possibility is int (f)()[2][2]
cdecl
or simply int f()[2][2]

If you want to omit one or both dimensions, you should return pointer with dimensions or better spanpack or vector.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
2

You can return a pointer to the beginning of the 2d array since the elements are all next to each other in memory.

int* return2dArray()
{
    static int a[2][2] = {{1, 2}, {4, 5}};
    return &a[0][0];
}

int main()
{
    auto x = return2dArray();

    for (int y = 0; y < 4 ; y++)
    {
        cout << "y is = " << x[y] << endl;    
    }    
}

Tried it out here

bigwillydos
  • 1,321
  • 1
  • 10
  • 15
  • Yeah, you can do that, but it's kinda gross. have you tried `auto return2dArray() { static int a[2][2] = {{1, 2}, {4, 5}}; return a; }`? It's nice, simple, and doesn't dump all of the type information. – user4581301 Jun 25 '19 at 06:05
  • As much as I want to use lambdas, I have to preserve how this legacy code is written (example above is just a representation). Thanks!! – kzaiwo Jun 25 '19 at 06:33
  • But, **pedantically**, you have UB when deferencing x[2] or use x[3], as `a` is not an array of 4 `int` (even if layout is compatible). – Jarod42 Jun 25 '19 at 08:11