I would like to store an array of fixed size in my contract storage, with a user-defined size, initialized to all 0s. Here's an example contract:

pragma solidity ^0.4.24;

contract Test {
    constructor(uint size) {
        uint[size] storage arr;
        for (uint i = 0; i < size; i++) { arr[i] = 0 }

My problem arises when declaring the array; remix gives this error:

TypeError: Invalid array length, expected integer literal or constant expression.

One workaround would be to declare the array outside of a function, but that would require it to be a dynamic array with no immediately accessible elements, which I don't want.

Is it possible to initialize arrays of this type in a constructor at all, and if so, how?

What's the alternate way to do the same?

1 Answer 1


I imagine you won't like this answer, but here goes anyway.

No. You can't.

I realize it's a contrived example, but the iteration over the array is also an anti-pattern. You did not explain your aversion to dynamic arrays and without further insight the use-case, it's not possible to know if mappings are possibly more appropriate or how to refactor the functions to ensure O(1) at any scale.

Hope it helps.

  • 1
    I ended up using a workaround - I appreciate your help. Commented Jul 6, 2018 at 22:10

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.