9

I can't find a way to manually initialize an array.

string[] public cool;

function constructor() {
    cool[0] = "one";
}

Won't execute, while

function constructor(){
    cool[cool.length++] = "one";
}

will.

What might be the reason behind it?

11

You can't assign a value to an array of size 0, you need to have enough space to write your value. It is true, you declared a variable size array but you still need to tell the VM to increase the array size before assign it.

You can increase array size and assign values in different ways:

  1. All-in-one (increase and set, my preferred) using push method, like this:

    cool.push("one");
    
  2. With two commands, setting length property and then setting the value

    cool.length = 1;
    cool[0] = "one";
    

Without really knowing it, you actually used the second way and you initialized manually the array length. In fact, using cool.length++ you increased to 1 the array size and, just after that, you passed 0 as key to the array (and note you passed 0 and not 1 because you used ++ after and not before the length variable). All this let you assign correctly "one" string inside the first position of the array.

Aside that, two suggestions:

  • Look at mapping if you don't want to mess to much with array sizes. You can do thing like that:

    mapping (int=>string) public cool;
    function testMapping() {
        cool[3] = "hello";
        cool[33] = "world";
        cool[333] = "!!";
    }
    

without worrying about sizes.

  • Don't use constructor as method name, it can be really misleading. If you really need a contract constructor, it must be named as the contract name. If you need an init function, name it init().

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.