I'm trying to work with 2D in-memory arrays in Solidity, in which the size is not known at compile time. I've noticed that if I define the array size as a constant
, then I can use this syntax, which compiles and returns the expected 10x10 array:
uint256 constant size = 10;
function initArray() public view {
uint256[size][size] memory arr;
// ...
}
However, if I define the size using a variable, I get problems:
uint256 size = 10;
function initArray() public view {
uint256[size][size] memory arr;
// ...
}
Which leads to: TypeError: Invalid array length, expected integer literal or constant expression.
So I then try to use the new
syntax, but I can't figure out how to use it for 2D arrays. First I try the simplest thing:
uint256 size = 10;
function initArray() public view {
uint256[][] memory arr = new uint256[][](size)(size);
// ...
}
This leads to an error: TypeError: Type is not callable
, which makes sense. But then, how do I define the size of the inner arrays? I then tried:
uint256 size = 10;
function initArray() public view {
uint256[][] memory arr = new uint256[][](size);
for (uint i; i < size; i++) {
arr[i] = new uint256[](size);
}
// ...
}
This compiles but creates some nonsense data structure. Can anyone provide some guidance? The fact that this is possible via constants leads me to think there's no fundamental barrier, I just can't figure out the syntax for passing size via a variable. Thank you!!