16

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.

8

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"; 
            x++;
        }
    }

    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

  • 1
    Huh, I never would've thought to check the doc FAQs. Nice find and interesting solution! – user9402 Jun 6 '17 at 13:35
  • 1
    Why I can't return a dynamic array of of bytes32 (bytes32[])? – Robert Zaremba Aug 21 '17 at 14:41
  • 2
    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. – Robert Zaremba Aug 21 '17 at 18:02
  • @RobertZaremba But isn't bytes32 an array itself? Then bytes 32[] is a two dimensional array – Andrey Mar 21 '18 at 14:16
  • 1
    @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 :) – Oliver Rydzi Dec 10 '18 at 17:38

Your Answer

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