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:
All-in-one (increase and set, my preferred) using push method, like this:
cool.push("one");
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().