7

I do not seem to be able to initialize a struct containing a string array. This is what I tried:

contract testStruct {
    struct stru{
        string[] s;
    }

    stru myStru;

    /*
    function add(string s) {
        string[] strAr; // Uninitialized storage pointer. Did you mean ' memory strAr'?
        strAr.push(s);
        myStru = stru(strAr);
    }
    */

    function add(string s) {
        string[] memory strAr; // just doesnt do anything, exception?
        strAr[0] = s;
        myStru = stru(strAr);
    }

    function getFirst(uint i) constant returns (string s) {
        s = myStru.s[0];
    }
}

The first version (commented out) gives me the compiler warning and does not seem to write anything to storage. The second one seems to run into an exception (I assume that looking at the gas consumption). Thus my question is: How do I initialize a structure containing a string array?

7

The other answer which didnt work brought me on track to find it out myself:

contract testStruct {
    struct stru{
        string[] s;
    }

    stru myStru;

    function add(string s) {
        myStru.s.push(s);
    }

    function getAt(uint256 i) constant returns (string s) {
        s = myStru.s[i];
    }
}
  • You don't need to assign the old struct myStru to the new sStruct. The following will also work stru sStruct;. Or to be explicit, you are creating a new storage variable for the struct stru storage newStru; – naddison Jul 10 '16 at 11:35
  • thank you @naddison I improved and shortened the answer. – Validity Labs - Sebastian Feb 11 '18 at 10:16
3

Try this approach. Create the struct, then add to the array:

stru sStruct = stru();
sStruct.s.push('hello');
  • 1
    Unfortunately that does not compile: Wrong argument count for function call: 0 arguments given but expected 1. stru sStruct = stru(); but you brought me on track, thanks! – Validity Labs - Sebastian May 2 '16 at 19:32

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.