# solidity two-dimentional dynamic array

for dynamic array in solidity

uint[][] public test;

how can I insert the dynamic element? if test.length is 3, does this mean test[3][] or test[][3]? if I insert an element,

test.length++; len=test.length; test[len][test[len].length++]=my_int;

is this correct? thanks

## 2 Answers

Both of them work.

``````pragma solidity ^0.5.0;

contract Test {

uint[3][] a;
uint[][3] b;

constructor () public {
/// Error
/// a[0] = [1, 2, 3, 4];
/// Correct
b[0] = [1, 2, 3, 4];

/// Error
/// b[4] = [1, 2];
/// Correct
a[4] = [1, 2];
}
}
``````

Which one is right depends on what you want to achieve. Do you want 3 arrays with an unkown number of members, or do you want an unknown number of arrays with 3 members each.

An example for the first option would be a vote where there are 3 parties. Each vote is added to one of the three parties.

An example for the second option would be a list of members in a club. For every member you have three entries: gender, age, location.

A "2D" array is treated as an array of arrays. For example, if you needed a 10 x 2, it would be a `uint[10]` in which each row is itself a `uint[2]`. Either dimension can be dynamic.

A common mistake is to reverse the order of the indexes. For example, a dynamic list of `uint[3]` would be:

`uint[3][] myArray;`

Later, when you want to set, say the 2nd element of row 100, it would be:

`myArray[100][2]` because there is a `uint[3]` stored in row 100 and we want the 2nd element in that array.

This may help you find your way around dynamic x dynamic. Remember, weird switcharoos happen if it seems like it's not working.

``````pragma solidity 0.5.0;

contract TwoD {

uint[][] public test;

function appendFirstOrderArray() public {
uint[] memory element;
test.push(element);
}

function appendSecondOrderElementAtRow(uint row, uint value) public {
test[row].push(value);
}

function getFirstOrderLength() public view returns(uint) {
return test.length;
}

function getSecondOrderLengthAtRow(uint row) public view returns(uint) {
return test[row].length;
}

}
``````

Hope it helps.