[Ethereum] Declaring a memory array of storage pointers in Solidity

memorymemory-pointersoliditystoragestorage-pointer

I would like to declare a variable as a memory array of pointers to storage arrays of uint256.

For example:

pragma solidity ^0.4.24;

contract A
{
    uint256[] public array0;
    uint256[] public array1;
    constructor () public
    {
        array0.push(123);
        array1.push(456);
    }
    function test() public
    {
        uint256[][] memory storageArrays = new uint256[][](2);
        storageArrays[0] = array0;
        storageArrays[1] = array1;

        storageArrays[0][0]++;
        storageArrays[1][0]--;
    }
}

I want this to change the values of array0 and array1, but they don't change because the storage arrays were implicitly copied to memory. This code only changes their copy in memory.

This is because both dimensions of the array are set to memory. I would like the first dimension of the array to be storage, and the second one memory

I tried to declare storageArrays like this:

uint256[] storage [] memory storageArrays = new uint256[][](2);

But it gives this syntax error:

ParserError: Expected identifier but got '['
uint256[] storage [] memory storageArrays = new uint256[][](2);
                  ^

Is it possible? If so, how? Thanks in advance.

Best Answer

Solidity, in a deliberate way, does not support memory pointers “a la C”, neither it has any pointer arithmetic in place. This means that incrementing or decrementing a pointer variable is not a meaningful operation. You can do something similar in assembly, but you must manage the whole thing at the lowest level possible and without thinking to be able to sync the solidity variables and the assembly variables for any future version of Ethereum protocol.

Related Topic