Solidity: Can you return dynamic arrays in a function?

  • I know I can return dynamic byte arrays in Solidity, such as in the following code:

    function createMemoryArray(uint size) returns (bytes) {
        // Dynamic memory arrays are created using `new`:
        uint[2][] memory arrayOfPairs = new uint[2][](size);
        // Create a dynamic byte array:
        bytes memory b = new bytes(200);
        for (uint i = 0; i < b.length; i++)
            b[i] = byte(i);
        return b;

    But is there a way to return something like a dynamic array of strings? I feel like this is just an implementation detail in Solidity, but it would be great if it just serialized everything nicely for me.

  • Crema

    Crema Correct answer

    4 years ago

    Is it possible to return an array of strings ( string[] ) from a Solidity function?

    Not yet, as this requires two levels of dynamic arrays (string is a dynamic array itself). Doc

    However you can return an Array of Bytes32 ( fixed size of 32 byte) So you can try to do something like this ( you can copy paste on Remix to test it )

    pragma solidity ^0.4.11;
    contract ArrayOfBytes32 {
        address creator;
        bytes32[10] bytesArray; // size must be fixed
        function ArrayRR() 
            creator = msg.sender;
            uint8 x = 0;
            while(x < bytesArray.length)
                bytesArray[x] = "myString"; 
        function getArray() constant returns (bytes32[10])
            return bytesArray;
        function getValue(uint8 x) constant returns (bytes32)
            return bytesArray[x];

    Note that you will have to use web3.toAcsii() doc to convert the result if you use web3 to interact with your contract

    Huh, I never would've thought to check the doc FAQs. Nice find and interesting solution!

    Why I can't return a dynamic array of of bytes32 (`bytes32[]`)?

    You can return a dynamic array of of bytes32 (`bytes32[]`). What you can't is returning an object which combines two levels of dynamic arrays.

    @RobertZaremba But isn't bytes32 an array itself? Then bytes 32[] is a two dimensional array

    @Andrey Problem is with two levels of dynamic arrays, not a two dimensional arrays. You could have function return two dimensional array of 10 uints each without problem - but you cannot have two dimensional array where both arrays are dynamic. Type "bytes32" just indicate that it allocates 32 bytes in the memory, so it is not dynamic variable - you always know that it will take 32 bytes of memory, therefore it is static variable (cannot change size during runtime). That's why it works :)

    now it's just returning `0x00000000.... ,0x0000000....., ....` in solidity. Also, in newer version we have to add `memory` keyword in the return type which is creating the problem for me I think.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used