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?

BokkyPooBah
  • 40,274
  • 14
  • 123
  • 193
shultz
  • 1,091
  • 2
  • 13
  • 20

1 Answers1

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().
Giuseppe Bertone
  • 5,487
  • 17
  • 25
  • Note: The advice at the end about constructor classes is not correct as of Solidity 0.4.22+. "constructor()" now is the correct nomenclature. Check the documentation for the latest version: https://docs.soliditylang.org/en/v0.8.4/contracts.html#constructor – Nanolucas Apr 27 '21 at 20:29