Solidity Structs – Unable to Push Struct with Array to Another Array

remixsolidity

I'm aware there are some limitations on initializing empty arrays, but I can't find a solution to this issue I'm having.

I want to push a struct to an array. But since that struct itself contains an array of other structs, I'm unable to do it.

Here's my code:

pragma solidity ^0.4.23;
pragma experimental ABIEncoderV2;



contract simpleBet {

    struct Bettor {
        address wallet;
        uint betAmount;
        uint outcome;
        uint bettingTime;
    }

    struct bettingEvent {
        string name;
        string uid;
        uint startTime;
        uint endTime;
        Bettor[] bettors;
    }

    bettingEvent[] public bettingEvents;

    constructor() public {
    }


    function createBettingEvent(string _name, string _uid, uint _startTime, uint _endTime) public {

        bettingEvent memory _bettingEvent;
        _bettingEvent.name = _name;
        _bettingEvent.uid = _uid;
        _bettingEvent.startTime = _startTime;
        _bettingEvent.endTime = _endTime;
        _bettingEvent.bettors.push(Bettor(0,0,0,0));


        bettingEvents.push(_bettingEvent);
    }

}

TypeError: Member "push" is not available in struct simpleBet.Bettor memory[] memory outside of storage.

Best Answer

The issue is that you can't push to arrays that are located in memory. (Such arrays are not resizable.)

One possible fix is to just do the changes in storage:

function createBettingEvent(string _name, string _uid, uint _startTime, uint _endTime) public {
    bettingEvents.length += 1;
    bettingEvent storage _bettingEvent = bettingEvents[bettingEvents.length - 1];
    _bettingEvent.name = _name;
    _bettingEvent.uid = _uid;
    _bettingEvent.startTime = _startTime;
    _bettingEvent.endTime = _endTime;
    _bettingEvent.bettors.push(Bettor(0, 0, 0, 0));
}