iterate Array, Return Sum
We will examine two ways to iterate over a dynamic array passed as parameter into function, for which we must find the sum of elements.
1. Working with calldata
contract Question1 {
function iterateEachElementInArrayAndReturnTheSum(uint256[] calldata array) external pure returns (uint256) {
// TODO: Iterate each element in the array using only assembly
uint256 sum = 0;
assembly {
// locates the length of the array in the calldata
// copies it onto the stack
let len := calldataload(0x24)
for {let i := 0} lt(i, len) {i := add(i,1)}
{
// update free memory pointer
let ptr := add(mload(0x40), mul(i, 0x20))
// creates a new in-memory copy of the input array
// calldatacopy(copyToMemoryLocation, copyFromCallDataLocation, copySize)
//copyFromCallDataLocation: add(0x24, 0x20): location of len+32 bytes, to get first char
calldatacopy(ptr, add(add(0x24, 0x20), mul(i, 0x20)), 32)
sum := add(sum, mload(ptr))
}
}
return sum;
}
}Inspiration code
this will return the first element in the array
2. creates in-memory copy of the input calldata
References
Incorrect inspiration
Last updated