0

I have a question about writing functions in Solidity - I am trying to create an array of dog structs but I can't seem to get the function declaration correctly:

pragma solidity ^0.5.1;

contract MyContract {
    struct dog {
        string name;
        string ownername;
        int8 age;
    }
    dog[3] dogarray = dog(3);
    function setIndex(int index, string name, string ownername memory, int8 age) public {
        dogarray[index].name = name;
        dogarray[index].ownername = ownername;
        dogarray[index].age = age;
    }
    
}

I am getting the error contracts/MyContract.sol:11:64: ParserError: Expected ',' but got 'memory' function setIndex(int index, string name, string ownername memory, int8 age memory) public { ^----^ and I have tried putting memory after all the parameters and after some of the parameters (like I did above) but the error message persists.

When do we use the keyword memory? From what I understand, memory just means temporary storage (equivalent to the stack?) and storage means more permanent storage (heap?). I have seen functions being written without it and with it, so I just want to know if it is optional and when to and when not to use it.

0
  • Update 1: You have to write the argument like: string memory ownername.
  • Update 2: Use uint256 for indexing variables in arrays.
  • Update 3: You don't need to initialize the dogarray

Here the the updated code:

pragma solidity ^0.5.1;

contract MyContract {
    struct dog {
        string name;
        string ownername;
        int8 age;
    }

    dog[3] dogarray;

    function setIndex(
        uint256 index,
        string memory name,
        string memory ownername,
        int8 age
    ) public {
        dogarray[index].name = name;
        dogarray[index].ownername = ownername;
        dogarray[index].age = age;
    }
}

Check difference-between-memory-and-storage.

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.