5

I have changed a few things inside the function but the logic is the same still. Now, give an error in the compiler. I am USING TRUFFLE with VSC.

Former function:

function remove(uint ind) internal returns(address[]) {
    delete addressStorage[ind];
    for (uint j = ind; j<addressStorage.length;j++) {
        if (j==addressStorage.length-1) {
            break;
        }else {
            addressStorage[j] = addressStorage[j+1];
        }
    }
    addressStorage.length--;
    return addressStorage;
}

Actual:

function remove(uint ind, address[] array) internal returns(address[]) {
    delete array[ind];
    for (uint j = ind; j<array.length;j++) {
        if (j==array.length-1) {
            break;
        }else {
            array[j] = array[j+1];
        }
    }
    array.length--;
    return array;
}

Getting:

TypeError: Expression has to be an lvalue. array.length--; ^----------^

Any ideas? Thanks!

3 Answers 3

9

Memory is temporary. Storage is permanent. For example, you would perform intermediate computations using memory, and then save the result to storage.

There are defaults for the storage location depending on which type of variable it concerns:

  1. state variables are always in storage
  2. function arguments are in memory by default
  3. local variables of struct, array or mapping type reference storage by default
  4. local variables of value type (i.e. neither array, nor struct nor mapping) are stored in the stack

When you pass address[] array as a function argument, solidity will save it in memory i.e. it will make a copy of the array. Changes made will not be permanent.

Add "storage" in the argument to solve the error.

function remove(uint ind, address[] storage array) internal returns(address[]) {
delete array[ind];
for (uint j = ind; j<array.length;j++) {
    if (j==array.length-1) {
        break;
    }else {
        array[j] = array[j+1];
    }
}
array.length--;
return array;

}

1

This is my solution:

function _pullFromArray(uint[] storage arr, uint index) internal returns(uint[]) {
    for(uint i = index; i < arr.length - 1; i++) {
        arr[i] = arr[i+1];
    }
    if (index < arr.length) {
        delete arr[arr.length - 1];
        arr.length--;
    }
    return arr;
}
0

The problem is that in your previous version you were dealing with an storage array and now you are using a memory array.

As opposed to storage arrays, it is not possible to resize memory arrays by assigning to the .length member.

1
  • Yep...i realised maybe that was the problem. So, I have to create a remove function to resize each address array?
    – Jorge
    Dec 22, 2017 at 0:09

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.