Using assembly to loop and modify memory-array?

I'm trying to improve my assembly skills and so I'm trying to write a function that allows me to use assembly to read from one memory array variable and write into another memory array variable but 'm having difficulty.

function getArray() public pure returns(uint256[] memory) {
        uint256[] memory arrayOne = new uint256[](9);
        arrayOne[0] = 1;
        arrayOne[1] = 2;
        arrayOne[2] = 3;
        arrayOne[3] = 4;
        arrayOne[4] = 5;
        arrayOne[5] = 1;
        arrayOne[6] = 1;
        arrayOne[7] = 1;
        arrayOne[8] = 1;
        uint256[] memory arrayTwo = new uint256[](5);

        assembly {
            let len := mload(arrayTwo)
            for
                { let i := 0 }
                lt(i, len)
                { i := add(i, 1) }
            {
                // insert into arrayTwo
            }

        }

        return arrayTwo;
    }

I want to loop through arrayOne and insert the first 5 elements into arrayTwo.
My intent is to have arrayTwo = [1,2,3,4,5]

The arr length is mload(array) , you did right on this.
And the first value of arr is add(arr, 0x20), the second is add(arr, 0x40), and so on.
I did a bit change on for loop, and hope you can understand.

function getArray() public pure returns(uint256[] memory) {
        uint256[] memory arrayOne = new uint256[](9);
        arrayOne[0] = 1;
        arrayOne[1] = 2;
        arrayOne[2] = 3;
        arrayOne[3] = 4;
        arrayOne[4] = 5;
        arrayOne[5] = 1;
        arrayOne[6] = 1;
        arrayOne[7] = 1;
        arrayOne[8] = 1;
        uint256[] memory arrayTwo = new uint256[](5);

        assembly {
            let len := mload(arrayTwo)
            for
                { let i := 1 }
                lt(i, add(len, 1))
                { i := add(i, 1) }
            {   
                let a := mul(i, 0x20)
                mstore(add(arrayTwo, a), mload(add(arrayOne, a)))
            }

        }

        return arrayTwo;
    }
1 Like

In a uint256 array:

  • The 1st chunk of 32 bytes stores the length of the array
  • The 2nd chunk of 32 bytes stores the 1st uint256 value
  • The 3rd chunk of 32 bytes stores the 2nd uint256 value
  • The 4th chunk of 32 bytes stores the 3rd uint256 value
  • ...

So instead of i := 0, you should use let i := 32.

And instead of add(i, 1), you should use add(i, 32).

thank you @bca_service ! worked like a charm!!