I was looking at the documentation and was looking at arrays stored in memory. Now, the documentation said that arrays stored in memory cannot change their size using .push() or .pop() functions. This makes sense. What doesn't make sense is the difference between these two:

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Arrays {

    function test() public pure returns (uint[3] memory, uint[] memory) {
        uint[3] memory testArray;
        testArray[0] = 3;
        testArray[1] = 4;
        testArray[2] = 5;
        uint[] memory testArray2 = new uint[](3);
        testArray2[0] = 13;
        testArray2[1] = 14;
        testArray2[2] = 15;
        return (testArray, testArray2);

I understand that the uint[] memory testArray2 = new uint[](3); is a dynamic array whereas the uint[3] memory testArray; is a static array. But what's the difference? Are they the exact same thing since they are both of fixed size?

If they are different: when would I use each? What are the pros/cons to each one?

  • 1
    You should use static when you know when the data being stored is fixed. For example, to store weekdays or month names you should use static array. Dynamic is when you are storing names or something whose data size are not fixed. Since the size of static array is fixed you cannot use push or pop. Sep 23 at 3:52
  • Thank you @AbhishekSinha ! But, when it's in memory, you can't use push or pop anyway. So what's the difference then? Thanks! :)
    – tsnakejake
    Sep 23 at 3:58
  • Use static array when you know you don't have to add/remove any element. If you have to you must use dynamic array. In dynamic arrays you can use push and pop to add remove items. Sep 23 at 9:01
  • @AbhishekSinha Yes, but you can't use push and pop for arrays stored in memory. So my question is when would I use fixed/dynamic arrays for arrays stored in memory.
    – tsnakejake
    Sep 23 at 14:00
  • 1
    Okk..yes, in your case both are same. Since you are using memory keyword to store the data, the data will be flushed after the function execution is over. So here both the methods are equivalent. Sep 23 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.