# Returning 2D array with dynamic sizes from a function

This 2D array works when setting the array lenghts with constant values. But i'd prefer to use a dynamic array size:

``````function funWith2DArray(address[] array1,  address[] array2) public view returns (uint[50][50]) {
uint[50][50] memory result;
// ...
return result;
}
``````

This 1D array works, when dynamically setting the array length:

``````function funWith1DArray(address[] array1,  address[] array2) public view returns (uint[]) {
uint[] memory result = new uint[](array1.length * 2);
// ...
return result;
}
``````

How can I do a 2D array with dynamic lengths?:

``````function funWith2DArray_2(address[] array1,  address[] array2) public view returns (uint[][]) {
// Not valid syntax
// uint[][] memory result = new uint[][](array1.length * 2)(array1.length * 2);
// Not correct either, error: Identifier must be declared a constant
// uint[array1.length * 2][array1.length * 2] memory result;
return result;
}
``````

Note: This function must have the view modifier so I can call it (reading data only) without paying gas.

My current workaround is just cramming all the response data into one array and just knowing where to look to find it (which is okay)

It's not possible yet. See Solidity 0.4.21 FAQ here (search for "dynamic array") -> http://solidity.readthedocs.io/en/develop/frequently-asked-questions.html

It is also not possible to return string[] since technically it's also a 2-dim array.

• Ok, that makes sense. Fortunately, I'm only returning uints. For now, I'll stick with my workaround of returning all the values in one single array and just rely on knowing how to parse it on the other side. Feb 26, 2018 at 18:20

A good practice / workaround is to simply iterate over all values of that dynamically sized array till you don't get any return. Less beautiful for use in contracts, but not really problematic when implemented in dApps.

You still cannot return 2d array but there is a workaround.
Basically wrap the inner uint256 array in a struct and return an array from this struct.

``````contract Return2D {
struct Uint256ArrayWrapper {
uint256[] array;
}

function get2DArray(uint256 n, uint256 k) pure public returns (Uint256ArrayWrapper[] memory) {
Uint256ArrayWrapper[] memory array2d = new Uint256ArrayWrapper[](n);
for(uint256 i = 0; i < n; i ++) {
uint256[] memory array1d = new uint256[](k);
for(uint256 j = 0; j < k; j ++) {
array1d[j] = j;
}
array2d[i] = Uint256ArrayWrapper({array: array1d});
}

return array2d;
}

function use() pure public {
Uint256ArrayWrapper[] memory array2d = get2DArray(10, 10);

array2d[5].array[2];
array2d[5].array[3];
array2d[5].array[4];
array2d[0].array[2];
array2d[0].array[3];
array2d[0].array[4];
}
}
``````