Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ethereum Solidity, when changing an array length, I get "Value must be an lvalue". Why?

Tags:

ethereum

In Solidity, you can increase the size of an array to make room for a new member by using array.length++. But I'm getting an error:

Value must be an lvalue
like image 970
fivedogit Avatar asked Nov 21 '15 02:11

fivedogit


People also ask

How long can an array be solidity?

The maximum number that can be represented in Solidity is 2**256 and that is also the maximum number of elements that you can hold in any Solidity data structure.

What is difference between mapping and array in solidity?

Array: When to use one over the other. If you need to be able to iterate over your group of data (such as with a for loop), then use an array . If you don't need to be able to iterate over your data, and will be able to fetch values based on a known key, then use a mapping .

How do you remove an element from an array in solidity?

We can create a function remove() that will take an array's index as an argument. Then the function will set the index argument to the last element in the array. Simply, we will shift the index argument over the last element of the array. Then we will remove the last element by using the pop() method.


1 Answers

You can resize a dynamic array in storage (i.e. an array declared at the contract level) with “arrayname.length = ;” But if you get the “lvalue” error, you are probably doing one of two things wrong. You might be trying to resize an array in memory, or You might be trying to resize a non-dynamic array.

int8[] memory somearray;     // CASE 1
somearray.length++;          // illegal 

int8[5] somearray;           // CASE 2
somearray.length++;          // illegal 

IMPORTANT NOTE: In Solidity, arrays are declared backwards from the way you’re probably used to declaring them. And if you have a >=2D array with some dynamic and some non-dynamic components, you may violate #2 and not understand why. Note also that arrays are accessed the “normal” way. Here's are some examples of this "backward" declaration paradigm in action:

int8[][5] somearray;  // This is 5 dyn arrays, NOT a dyn array-of-arrays w/len=5
// so...
somearray[4];         // the last dynamic array
somearray[1][12];     // the 13th element of the second dynamic array
// thus...
somearray.length++;   // illegal. This array has length 5. Always.
somearray[0].length++;// legal
like image 120
fivedogit Avatar answered Nov 11 '22 00:11

fivedogit