pragma solidity ^0.4.18; contract Foo { struct Bar { address owner; uint[] x; } Bar[] public bars; function addOwner(address _a) public returns (uint) { Bar memory b; b.owner = _a; bars.push(b); return bars.length - 1; //return the index of the newly added owner } //you can use it to verify entered owner function getOwner(uint _i) public view returns (address) { return bars[_i].owner; } function addValue(uint _i, uint _value) public returns (uint) { bars[_i].x.push(_value); return bars[_i].x.length - 1; //return the index of the newly added value } //you can use it to verify entered values function getValue(uint _i, uint _j) public view returns (uint) { return bars[_i].x[_j]; } function foobar(address a) public { Bar memory b; b.owner = a; //When 'b' is pushed to 'bars' array: // (1) 'b' will be converted from memory to storage. // (2) And 'x' inside it will be initialized automatically. bars.push(b); } function foobar2(address a, uint x0) public { Bar memory b; b.owner = a; bars.push(b); //b.x[0] = x0; It generate error since b.x is a memory array that is not initialized! bars[bars.length - 1].x.push(x0); //Will work fine! } function foobar3(address a) public { Bar memory b = Bar(a, new uint[](0)); bars.push(b); } function foobar4(address a, uint[] _x) public { Bar memory b = Bar(a, _x); bars.push(b); } //Consume more gas than foobar4 function foobar5(address a, uint[] _x) public { Bar memory b; b.owner = a; bars.push(b); Bar storage c = bars[bars.length - 1]; // Get the newly added instance of the storage struct for (uint i = 0; i < _x.length; i++) { c.x.push(_x[i]); } } }
0.4.18