Dynamic Memory Arrays
Part of the Fundamentals section of Coddy's Solidity journey. Lesson 37 of 53.
Use new uint256[](length) to allocate an array in memory with a length chosen at runtime. Its elements start at zero. Although the type uses empty brackets, the allocated memory array cannot be resized with push or pop.
The statements in this excerpt run inside the provided main function.
uint256[] memory values = new uint256[](3);
values[1] = 19;
console.log(values.length);
console.log(values[0]);The array has three slots and only the middle slot was assigned. Its first element stays zero. The length property reports how many elements exist, not the value of the last element.
A newly allocated uint256 memory array starts with zero-valued elements.
Challenge
EasyAllocate a memory array of length n, set its last element to marker, then print its length and last element. n is between 1 and 8.
The tests pass arguments to main in this order: uint256 n, uint256 marker. Each test starts with fresh contract state.
Use console.log for the requested output. Print only the requested values, one per line, with no extra labels unless the task specifies them.
Try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "forge-std/console.sol";
contract Main {
function main(uint256 n, uint256 marker) external view {
// Write your solution here.
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
Practice on your own: Solidity playground