-4

Can you return in c++ a two dimensional array without using vectors or pointers?

I found this answer but I don't want to manage the ram myself when using pointsers https://stackoverflow.com/a/4172103/4954387

Patrick
  • 29
  • 1
  • 6
  • 2
    Use `std::array – Hatted Rooster Nov 23 '17 at 20:50
  • 5
    The answer you've link is terrible. Arrays can't be passed by value in c++. That's one of the reasons [`std::array`](http://en.cppreference.com/w/cpp/container/array) exists. The alternative would be to accept an array where the results can be written as an additional argument to your function. Is there a particular reason why you don't want to use `std::vector`? – François Andrieux Nov 23 '17 at 20:53
  • 2
    Why no vectors? – Galik Nov 23 '17 at 21:19
  • It is a condition in extra exercises from university. This is the smallest part of the execercise, but it is also the hardest part. – Patrick Nov 24 '17 at 11:12

1 Answers1

2

Can you return in c++ a two dimensional array without using vectors or pointers?

Only if the size is known at compile time and only if you wrap the array in a class type. Just like one-dimensional arrays. You cannot return arrays directly.

struct Array
{
    int array[2][3];
};

Array f()
{
    return Array { 1, 1, 1, 2, 2, 2 };
}

int main()
{
    auto const array = f();
}

If you consider using a class like Array, think twice and mind that the standard library already offers std::array for that.

If you don't know the size at compile time, drop the "without using vectors" requirement and use std::vector.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62