[Ethereum] How to initialized struct with member variable type mapping

ethereumjsolidity

I have a problem with the below code, specifically samplestruct2

struct samplestruct1 {
    string name;
}
struct samplestruct2{
    string name;
    mapping (int => samplestruct1) s1s;
}

function createSampleStruct2(string name) {
    samplestruct2 s2;
    s2.name = name;
    ...
}

samplestruct2 s2 is giving me a warning : "uninitilized storage pointer"

I also tried samplestruct2 s2 = samplestruct2(name), it gives me also an error

Best Answer

Because s2 is a struct being instantiated in the function rather than the contract, solidity will make it a storage member of the contract itself. This is unlike other primitive types which default to memory in the local scope of the function. The warning is a prompt to make a proper declaration. Either declare s2 in the contract or use memory to make s2 local to createSampleStruct2(string name)

contract c {
    struct samplestruct1 {
        string name;
    }
    struct samplestruct2{
        string name;
        mapping (int => samplestruct1) s1s;
    }

    samplestruct2 s2; // declared in contract storage scope.

    function setS2Name(string name) {
        s2.name = name;
    }

    function newS1(int key, string name) {
        samplestruct1 memory s1; // using memory for structs before commiting to storage.
        s1.name = name;
        s2.s1s[key] = s1;
    }
}
Related Topic