The fixed arrays doesn't have push
member, you need to use the index to set the value:
pragma solidity ^0.4.24;
contract Garbage {
address[3] public addresses;
uint idx;
function addAddress(address _address) public {
require(idx < addresses.length);
addresses[idx] = _address;
idx++;
}
}
Solidity creates getter functions for public state variables automatically. For example, the following will work:
contract A {
uint256 public foo = 1;
}
contract B {
A a;
function getFoo() public view returns (uint256) {
return a.foo();
}
}
In the case of arrays however, you can only get a single element from the array, rather than the entire array. From the Solidity documentation:
If you have a public
state variable of array type, then you can only retrieve single elements of the array via the generated getter function. This mechanism exists to avoid high gas costs when returning an entire array. You can use arguments to specify which individual element to return, for example data(0)
. If you want to return an entire array in one call, then you need to write a function.
Basically, while you can do the following:
contract A {
uint256[] public foo;
}
contract B {
A a;
function getFoo() public view returns (uint256) {
return a.foo(0); // Get item at index 0 from the array
}
}
You cannot use a.foo()
to read the entire array, and you will have to use a getter function like this for example:
contract A {
uint256[] public foo;
function getFooLength() public view returns (uint256) {
return foo.length;
}
}
contract B {
A a;
function getFoo() public view returns (uint256) {
return a.getFooLength();
}
}
Best Answer
You need to use an array in storage because it is not possible to resize memory arrays.
Otherwise you need to define the size of the array during initialization: