how to return 2d array?

Know how to return 1d array, can not find solution for 2d array
Cant use vector
Know how to return 1d array
You probably just know how to return the pointer, if you can't return a higher dimension array.

The trick is to return an object. So define your 2D array as an object; you can use std::array<std::array<T, NCOLS>, NROWS>, or a vector equivalent or a struct/class. Then just return that.

If you stick with pointers, you'll loose dimension sizes.

e.g.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <vector>
#include <iostream>

using int_d2array_t = std::vector<std::vector<int>>;

int_d2array_t create_2darray(size_t nrows, size_t ncols, int val = -1) {
    return int_d2array_t( nrows, std::vector<int>(ncols, val) );
}

int main() {
    constexpr size_t nrows{12};
    constexpr size_t ncols{6};
    auto int2d = create_2darray(nrows, ncols);

    std::cout << "nrows=" << int2d.size()
        << " ncols=" << int2d[0].size()
        << '\n';
}


EDIT: Just saw this bit,
Cant use vector
Is this homework?
Last edited on
don't return 2D array, instead pass it as a reference to function parameter.
if you know the dimensions (compile time constant 2d array?) you can return it as 1d and cast it back with some ugly tricks. But that is so very C and weird code.
There are a lot of reasons why 1d mapped to 2d is easier to work with (you manually index the 1d to make it '2d' exactly the same way C does it).

if you need to see the casting junk I can figure it out again, but its not a good idea.
Last edited on
Know how to return 1d array, can not find solution for 2d array
Cant use vector


You can't return a c-style array of any dimensions. All you can do is return a pointer to the first element.

You can wrap an array inside of a struct and return that. But the C++ way is to either use std::vector or std:::array. Why can't you use these?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

struct MyArray {
	int arr[2][3] { };
};

MyArray func1() {
	MyArray myarr;

	for (auto r : { 0, 1 })
		for (auto c : { 0, 1, 2 })
			myarr.arr[r][c] = r + c;

	return myarr;
}

int main() {
	const auto arr1 { func1() };

	for (auto r : { 0, 1 }) {
		for (auto c : { 0, 1, 2 })
			std::cout << arr1.arr[r][c] << ' ';

		std::cout << '\n';
	}
}

Registered users can post here. Sign in or register to post.