# Why cannot insert elements dynamically into 2D memory array

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?

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;
}
}
``````
• Thanks a lot for the answer! I will play around with it. Dec 30, 2022 at 13:14