I am reading the solidity docs but there is a part I don't really understand.

In this example:

pragma solidity ^0.4.0;

contract C {
    uint someVariable;
    uint[] data;

    function f() public {
        uint[] x;
        data = x;

the doc says that "The type of the local variable x is uint[] storage, but since storage is not dynamically allocated, it has to be assigned from a state variable before it can be used."

I don't really understand what does it mean by "storage is not dynamically allocated" and why the method "x.push(2)" does change the "somevariable"

Any help is appreciated.

1 Answer 1


why the method "x.push(2)" does change the "somevariable"

Because when you thought you declared memory variable as uint[] x;, compiler interpreted it as storage pointer. Which by default points at storage slot 0 where somevariable exist.

This happens because you cannot declare storage variable inside of the function; you can either declare memory variable or create storage pointer.

To declare array in memory it must be fixed sized and follow this syntax:

function f() public {
    uint[] memory x = new uint[](3); // size of array in round brackets 
    x[0] = 2; // array.push() is not allowed
    data = x;
  • Thank you. So because we cannot create storage variables inside a function, if you declare one, you must give a pointer to a pre-existing one that was declared outside the function. Otherwise will point to the first one in the storage slot 0 and you will modify the wrong variable. Lesson learned Feb 5, 2018 at 14:24
  • Good catch! Easy to ignore this issue. Jun 20, 2018 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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