0

As far I know, new address[](number) creates an fixed sized array of that number initialized with zero. But how in this line Room memory room = Room(new address[](0), 0, 0); Room struct is taking an empty array and later how an address is going to be put there?

pragma solidity ^0.4.18;

contract StructArrayInit {
  
  event OnCreateRoom(address indexed _from, uint256 _value);
  
  struct Room {
    address[] players;       
    uint256 whosTurnId;
    uint256 roomState;
  }  
  
  Room[] public rooms;

  function createRoom() public {
      Room memory room = Room(new address[](0), 0, 0);
      rooms.push(room);
      rooms[rooms.length-1].players.push(msg.sender);

      OnCreateRoom(msg.sender, 0);
  }
  function getRoomPlayers(uint i) public view returns (address[]){
      return rooms[i].players;
  }
}
Hasnat Pie
  • 17
  • 4

1 Answers1

0

In this statement:

Room memory room = Room(new address[](0), 0, 0);
rooms.push(room);

In the first line, he declared a Room struct variable with the following value: 0,0 and 0. This means that players, whosTurnId, roomState struct variable have zero values.

With the second line, he pushed inside rooms array, Room struct variable created previously. With this statement:

rooms[rooms.length-1].players.push(msg.sender);

he took the last element of array (what he has entered) then push inside players array inside Room struct the msg.sender value. If you want to insert more address inside players array, you can use this statement:

rooms[rooms.length-1].players.push([address]);
Antonio Carito
  • 1,287
  • 1
  • 5
  • 10