PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 28, 2022

[FIXED] How a struct is taking an empty array and later how an address is going to be put there?

 July 28, 2022     blockchain, ethereum, remix, solidity, web3js     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing