'Cannot assign values to multi-dimensional array in solidity

I'm trying to use this function but I am getting an ambiguous error. All I get is "errorCode":"32"

Is there a reason this does not work? Am I missing something?

function generatePoints(uint256 pointsCount) public view returns (uint256[][1] memory) {
  uint256[][1] memory points;
  for(uint256 i; i < pointsCount; i++) {
    points[i][0] = 1;
  }

  return points;
}

This doesn't seem to work either

function _generateXPoints(uint256 pointsCount) public view returns (uint256[] memory) {
    uint256[] memory points;

    for(uint256 i; i < pointsCount; i++) {
      points[i] = 1
    }

    return points;
  }


Solution 1:[1]

Error code 0x32 is generated when you try accessing an array at an out-of-bounds index (solidity docs).

Indeed this dynamic memory array is created without allocating a length:

// this will have zero length
uint256[] memory points;

Note that it is not possible to resize memory arrays (docs), so the length must be specified during the declaration. In our case this should work:

function _generateXPoints(uint256 pointsCount) public view returns (uint256[] memory) {
    uint256[] memory points = new uint256[](pointsCount);

    for(uint256 i; i < pointsCount; i++) {
      points[i] = 1;
    }

    return points;
}

Returning to the multidimensional array. In solidity uint256[x][y] represents y arrays of length x. Also it's important to keep in mind that indices are accessed in the opposite direction of the declaration. So our array can be generated as:

uint256[][1] memory points;
points[0] = new uint256[](pointsCount);

so by generating the "external" array first (length fixed to 1) and then the internal ones. In conclusion:

function generatePoints(uint256 pointsCount) public view returns (uint256[][1] memory) {
    uint256[][1] memory points;
    points[0] = new uint256[](pointsCount);
    for(uint256 i; i < pointsCount; i++) {
        points[0][i] = 1;
    }

    return points;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1