[Ethereum] How to create a simple fixed-size array

contract-developmentsolidity

I feel like this is a stupid question, but I cannot find the answer. Readthedocs.io states:

"An array of fixed size k and element type T is written as T[k]"

But when I create the following simple code, it does not work. Remix tells me "Member "push" not found or not visible after argument-dependent lookup in address[3] storage ref".

pragma solidity ^0.4.24;

contract Garbage {

address[3] public addresses;


function addAddress(address _address) public {

    addresses.push(_address);

}

Removing the 3 gets rid of the error, but is then no longer a fixed array.

Best Answer

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++;
    }
}