Issue
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;
}
}
Solution
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]);
Answered By - Kerry99 Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.