Is there a mistake in the way I initialize Bar b in the function foobar?
contract Foo {
struct Bar {
address owner;
uint[] x;
}
Bar[] public bars;
function foobar(address a) public {
Bar storage b = Bar(a, new uint[]) // will that be an array in storage?
bars.push(b)
}
}
Best Answer
There is no need to initialize
storage
arrays in Solidity. Onlymemory
arrays has to be initialized before usage.So in your case, no need to initialize
x
insideBar
as long as you are not assigning a value to one of thex
indexes inside yourfoobar
. Actually, making initialization in your code will consume gas for no reason.The following code works well for your case:
However, if you need to access x and push some value you can use
push
:Actually, you can still initialize your memory array, as an empty one, as follow:
Last thing to mention is that: If you have multi values, that you need to insert to your
x
array, then you can do this as follow:Or as follow. But, this will consume more gas:
Check full code at the nice EthFiddler: https://ethfiddle.com/fQI6Khgz3E