7

I have the following contract code example:

contract C {

    struct A {
        uint256 a;
        uint256 b;
    }

    struct B {
        A ax;
        uint256 c;
    }

    struct C {
        string name;
        B[] bs;
    }

    function init() {
        C memory c;
        B memory b;
        A memory a;

        a.a = 10;
        a.b = 20;

        b.ax = a;
        b.c = 30;

        c.name = "Test test test";
        c.bs[0] = b;
    }
}

Why can't I use push for the last statement

 c.bs[0] = b;

:

c.bs.push(b);

It throws the following error:

Untitled:30:9: Error: Member "push" is not available in struct B memory[] memory outside of storage.
        c.bs.push(b);
        ^-------^

but bs is an array of structures.

  • Not completely related to the original question but to comment on Roland's comment: > Memory arrays have always a fixed length. Memory arrays can have variable length by initializing them with the new keyword. solidity.readthedocs.io/en/develop/types.html#arrays – atc Aug 16 '17 at 21:08
9

Push is available only on storage arrays, that is member/ state variables and not in memory arrays, that is local variables:

push: Dynamic storage arrays and bytes (not string) have a member function called push that can be used to append an element at the end of the array. The function returns the new length.

http://solidity.readthedocs.io/en/latest/types.html

  • So it's not possible to initialize a struct that contains an array and is stored in memory and then later append it as an element to an array in storage? – Sebi Jul 19 '16 at 15:26
  • 1
    from what I understand this is perfectly possible using push, but not the other way around. Memory arrays have always a fixed length. – Roland Kofler Jul 19 '16 at 15:33

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.