0
0
Blockchain / Solidityprogramming~15 mins

Arrays (fixed and dynamic) in Blockchain / Solidity - Deep Dive

Choose your learning style9 modes available
Overview - Arrays (fixed and dynamic)
What is it?
Arrays are collections that store multiple values in a single variable. Fixed arrays have a set size that cannot change after creation, while dynamic arrays can grow or shrink during the program's execution. In blockchain programming, arrays help organize data like lists of addresses or transaction details efficiently. They allow you to keep related information together and access it by position.
Why it matters
Without arrays, managing multiple pieces of related data would be complicated and inefficient, especially on blockchains where storage and gas costs matter. Arrays let you store and retrieve data in an organized way, saving space and making your smart contracts easier to write and understand. Without them, you would need many separate variables, making your code bulky and costly.
Where it fits
Before learning arrays, you should understand basic variables and data types. After arrays, you can learn about mappings and structs, which are other ways to organize data in blockchain programming. Arrays are a foundation for handling collections of data in smart contracts.
Mental Model
Core Idea
An array is like a row of mailboxes where each box holds one item, and you can find any item by its position number.
Think of it like...
Imagine a row of numbered lockers at a gym. Each locker can hold one person's belongings. Fixed arrays are like lockers with a fixed number of boxes, while dynamic arrays are like lockers where boxes can be added or removed as needed.
Fixed Array (size 4):
┌─────┬─────┬─────┬─────┐
│  0  │  1  │  2  │  3  │  Indexes
├─────┼─────┼─────┼─────┤
│val0 │val1 │val2 │val3 │ Values
└─────┴─────┴─────┴─────┘

Dynamic Array (size can change):
┌─────┬─────┬─────┐ ... ┌─────┐
│  0  │  1  │  2  │ ... │ n-1 │  Indexes
├─────┼─────┼─────┤     ├─────┤
│val0 │val1 │val2 │ ... │valn │ Values
└─────┴─────┴─────┘     └─────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Fixed-Size Arrays
🤔
Concept: Fixed arrays have a set number of elements that cannot change after creation.
In blockchain smart contracts, you can declare a fixed array by specifying its size. For example, an array of 3 unsigned integers holds exactly 3 numbers. You access elements by their index, starting at 0. Example: uint[3] fixedArray; fixedArray[0] = 10; fixedArray[1] = 20; fixedArray[2] = 30; Trying to add a fourth element causes an error.
Result
You get a container with exactly 3 slots, each holding a number. Accessing fixedArray[1] returns 20.
Understanding fixed arrays helps you manage data when you know the exact number of items upfront, which saves storage and gas on blockchain.
2
FoundationBasics of Dynamic Arrays
🤔
Concept: Dynamic arrays can change size during contract execution, allowing flexible data storage.
Dynamic arrays start empty or with some elements but can grow or shrink. You can add elements using the push() function and remove elements by changing the array length. Example: uint[] dynamicArray; dynamicArray.push(5); dynamicArray.push(15); Now dynamicArray has 2 elements: 5 and 15.
Result
You have a flexible list that can hold any number of elements, growing as needed.
Dynamic arrays let your contract handle changing data sizes, which is common in real blockchain applications like user lists or transaction logs.
3
IntermediateAccessing and Modifying Array Elements
🤔Before reading on: Do you think you can change an element in a fixed array after creation? Commit to yes or no.
Concept: You can read and write to any element by its index, but fixed arrays cannot change size, while dynamic arrays can.
Both fixed and dynamic arrays allow you to access elements by their index. For example, fixedArray[1] = 50 changes the second element. For dynamic arrays, you can also add or remove elements. Example: fixedArray[1] = 50; // changes value uint val = dynamicArray[0]; // reads value Remember, accessing an index outside the array size causes an error.
Result
You can update or read any element inside the array bounds safely.
Knowing how to access and modify elements is key to using arrays effectively and avoiding runtime errors.
4
IntermediateArray Length and Gas Costs
🤔Before reading on: Do you think increasing a dynamic array's size costs more gas than accessing an existing element? Commit to yes or no.
Concept: Array length tells how many elements are stored, and changing size costs gas on blockchain.
You can get the number of elements with array.length. For dynamic arrays, pushing new elements increases length and costs gas because it uses storage. Reading elements costs less gas. Example: uint len = dynamicArray.length; dynamicArray.push(100); // costs gas Removing elements by reducing length also costs gas.
Result
You understand that growing arrays uses blockchain resources, so use them wisely.
Knowing gas costs helps you write efficient smart contracts that save money and run faster.
5
IntermediateIterating Over Arrays Safely
🤔Before reading on: Is it safe to loop over a dynamic array without checking its length first? Commit to yes or no.
Concept: You should always use array length to control loops to avoid errors or excessive gas use.
When looping through arrays, use the length property to avoid going out of bounds. Example: for (uint i = 0; i < dynamicArray.length; i++) { // process dynamicArray[i] } Avoid hardcoding loop limits because array size can change.
Result
Your loops run safely and efficiently, preventing crashes or wasted gas.
Using length in loops prevents common bugs and ensures your contract handles arrays of any size.
6
AdvancedMemory vs Storage Arrays
🤔Before reading on: Do you think arrays declared inside functions always save data permanently on blockchain? Commit to yes or no.
Concept: Arrays can be stored in memory (temporary) or storage (permanent), affecting behavior and gas costs.
In Solidity, arrays declared inside functions default to memory, which is temporary and cheaper. Storage arrays persist on blockchain and cost more gas. Example: function foo() public { uint[] memory tempArray = new uint[](3); // temporary uint[3] storage permArray = fixedArray; // permanent } Modifying memory arrays does not change contract state.
Result
You know when changes affect blockchain data and when they are temporary.
Understanding memory vs storage arrays is crucial for writing correct and gas-efficient smart contracts.
7
ExpertGas Optimization with Fixed and Dynamic Arrays
🤔Before reading on: Is using dynamic arrays always more gas-expensive than fixed arrays? Commit to yes or no.
Concept: Choosing between fixed and dynamic arrays impacts gas costs; sometimes fixed arrays save gas, but dynamic arrays can be optimized with careful use.
Fixed arrays use less gas when size is known and constant because storage is allocated once. Dynamic arrays cost more when resizing but can be optimized by minimizing push/pop operations and using unchecked loops. Example: // Using unchecked to save gas in loops for (uint i = 0; i < arr.length; ) { // process unchecked { i++; } } Also, avoid unnecessary copying between memory and storage.
Result
You can write smart contracts that balance flexibility and cost by choosing the right array type and coding style.
Knowing gas tradeoffs helps you build scalable blockchain apps that save users money and run efficiently.
Under the Hood
Arrays in blockchain smart contracts are stored in contract storage, which is a key-value store. Fixed arrays allocate a fixed number of storage slots, each holding one element. Dynamic arrays store their length in one slot and elements sequentially in others. When you push to a dynamic array, the length slot updates and a new storage slot is assigned. Reading or writing accesses these slots by calculating the correct storage key based on the array's base slot and index.
Why designed this way?
This design balances simplicity and efficiency. Fixed arrays are simple and cheap when size is known. Dynamic arrays provide flexibility needed for real-world data but require extra storage management. The storage slot calculation allows efficient random access without complex indexing structures, fitting blockchain's limited and costly storage model.
Contract Storage Layout:

Fixed Array (size 3):
Slot 0: element 0
Slot 1: element 1
Slot 2: element 2

Dynamic Array:
Slot X: length (number of elements)
Slot keccak256(X) + 0: element 0
Slot keccak256(X) + 1: element 1
Slot keccak256(X) + 2: element 2

Access flow:
Caller -> Array base slot -> Calculate element slot -> Read/Write storage
Myth Busters - 4 Common Misconceptions
Quick: Do you think dynamic arrays automatically shrink when you remove elements? Commit to yes or no.
Common Belief:Dynamic arrays automatically shrink their size when you remove elements.
Tap to reveal reality
Reality:Dynamic arrays do not automatically shrink; you must manually reduce the length or remove elements carefully.
Why it matters:Assuming automatic shrinking can cause unexpected data to remain, leading to bugs or security issues.
Quick: Do you think accessing an array index outside its length returns zero or null safely? Commit to yes or no.
Common Belief:Accessing an out-of-bounds index in an array returns zero or null without error.
Tap to reveal reality
Reality:Accessing out-of-bounds indexes causes a runtime error and reverts the transaction.
Why it matters:Not checking bounds can cause your smart contract to fail unexpectedly, wasting gas and causing user frustration.
Quick: Do you think arrays declared inside functions always save data permanently on blockchain? Commit to yes or no.
Common Belief:Arrays declared inside functions always store data permanently on the blockchain.
Tap to reveal reality
Reality:Arrays declared inside functions are usually in memory and temporary; they do not persist after function execution.
Why it matters:Misunderstanding this leads to bugs where data changes are lost, causing incorrect contract behavior.
Quick: Do you think fixed arrays can be resized after deployment? Commit to yes or no.
Common Belief:Fixed arrays can be resized later by changing their length property.
Tap to reveal reality
Reality:Fixed arrays have a fixed size set at compile time and cannot be resized.
Why it matters:Trying to resize fixed arrays causes errors and wastes gas, limiting contract flexibility.
Expert Zone
1
Dynamic arrays store their length in a dedicated storage slot, and elements start at a keccak256 hash of that slot, enabling efficient random access.
2
Copying large dynamic arrays between memory and storage is expensive; minimizing such operations is key for gas optimization.
3
Unchecked loops can save gas but require careful bounds checking to avoid vulnerabilities.
When NOT to use
Avoid dynamic arrays when the maximum size is known and fixed arrays suffice, as fixed arrays save gas. For complex key-value data, use mappings instead of arrays. When order does not matter, consider using mappings for cheaper lookups. For very large datasets, off-chain storage with on-chain references is better.
Production Patterns
In real smart contracts, fixed arrays are used for constants or small fixed lists like token decimals. Dynamic arrays store user-generated data like addresses or votes. Developers often combine arrays with mappings for efficient existence checks. Gas optimization patterns include limiting array size, batching operations, and careful memory vs storage management.
Connections
Linked Lists
Alternative data structure for dynamic collections with efficient insertions/removals.
Understanding arrays helps contrast their fixed indexing with linked lists' pointer-based structure, highlighting tradeoffs in blockchain data management.
Database Tables
Arrays are like rows in a table where each element is a record.
Knowing arrays clarifies how blockchain stores structured data similarly to databases but with stricter size and cost constraints.
Human Memory Storage
Arrays resemble how humans organize information in ordered lists for quick recall.
Recognizing this connection helps appreciate why arrays are intuitive and efficient for organizing data both in code and cognition.
Common Pitfalls
#1Trying to access or modify an array element outside its bounds.
Wrong approach:uint val = dynamicArray[10]; // when dynamicArray.length < 11
Correct approach:if (dynamicArray.length > 10) { uint val = dynamicArray[10]; }
Root cause:Not checking array length before accessing elements leads to runtime errors and transaction reverts.
#2Assuming dynamic arrays shrink automatically after removing elements.
Wrong approach:dynamicArray.pop(); // expecting length to reduce and element removed safely without further action
Correct approach:dynamicArray.pop(); // valid // But to remove element at index i, shift elements manually or overwrite and pop last
Root cause:Misunderstanding that pop only removes the last element and that removing arbitrary elements requires manual handling.
#3Declaring arrays inside functions and expecting data to persist after function ends.
Wrong approach:function foo() public { uint[] memory tempArray = new uint[](3); tempArray[0] = 1; } // expecting tempArray to be stored permanently
Correct approach:contract-level storage array declared outside functions stores data permanently. uint[] storageArray; function foo() public { storageArray.push(1); }
Root cause:Confusing memory (temporary) and storage (permanent) locations in Solidity.
Key Takeaways
Arrays are essential for grouping multiple related values in blockchain smart contracts, with fixed arrays having a set size and dynamic arrays able to grow or shrink.
Accessing array elements by index requires careful bounds checking to avoid runtime errors and wasted gas.
Dynamic arrays store their length and elements in specific storage slots, making their management more complex but flexible.
Understanding the difference between memory and storage arrays is critical for correct and efficient smart contract behavior.
Choosing between fixed and dynamic arrays impacts gas costs and contract flexibility, so use them wisely based on your data needs.