1

I have some issues with understanding exactly how the arrays and memory works in solidity, but I found this nice question that kind of help me to understand some parts - Solidity 2D in-memory array with size defined by a variable

I see how the 2D array can be initialized, but why we have to mention the exact size for the first dimension (X axis)?

In my case, I know precisely how big the array can be, so it is fine, but what if I do not know how many elements I can have on X axis?

1 Answer 1

2
+50

Actually, that's not true. You could have the size of all dimensions in the array be determined at runtime as follows:

pragma solidity ^0.8.15;

contract Demo {
    // Creates an array with height `n` and width `m`. 
    function makeArr(uint n, uint m) public pure returns (int[][] memory) {
        // Define the array with first dimension being of size n.
        int[][] memory arr = new int[][](n);
        // Initialize all the array rows.
        // Notice that each row is basically a 1D array of size `m`.
        for(uint i; i < n; i++) {
            arr[i] = new int[](m);
        }

        // At this point, you have a fully initialized 2D array of size n x m.
        // You could access and set each element in the array.
        // For example, here is how to set the value for the element [0][0]:
        arr[0][0]=10;
        return arr;
    }
}
1
  • Thanks a lot for the answer! I will play around with it.
    – Vitomir
    Dec 30, 2022 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.