0
pragma solidity >=0.5.0 <0.7.0;
contract Mycontract{
    uint256 a;
    struct User
    {  string name; }
    User[] users;
    function foo() public{
      User storage user=users[0];
      user.name="hey";
    }
    function get() public view returns(string memory)
    {   return users[0].name; }
}
1

It is caused by this : User storage user=users[0];

You try to assign to user the first element of the users array but you can't access an empty array.

If you want to push your object into the array you can use array.push().

4
  • Do User storage user = User("hey) then users.push(user). – clement Jul 29 '20 at 8:26
  • it is giving me the following error: Type struct Mycontract.User memory is not implicitly convertible to expected type struct Mycontract.User storage pointer. User storage user= User("hey"); ^----------------------------^ – user61878 Jul 29 '20 at 8:44
  • Change "storage" to "memory". – clement Jul 29 '20 at 8:50
  • yes its working but can you please tell me the reason for doing so? – user61878 Jul 29 '20 at 9:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.