6

How to return an array from a function in solidity. Function is given :

function getTrackDetailsNew(bytes32 _iswc) public constant returns(bytes32[] isrc) {  
    bytes32 s;
    for(uint8 i=0;i<count;i++) {
        s = track[isrcKeyArray[i]].iswc;
        if(s == _iswc) {  
            isrc[i] = isrcKeyArray[i];  
        }  
    }  
    return isrc;  
}
sruthi23
  • 361
  • 4
  • 15
  • Can you tell us what is the error you get? – Itération 122442 Jan 12 '18 at 05:54
  • The error I am getting is : call to Trackdata.getTrackDetailsNew errored: VM error: invalid opcode. invalid opcode The execution might have thrown. Debug the transaction to get more information. – sruthi23 Jan 12 '18 at 06:19

3 Answers3

2

The problem lies in you returning a dynamic array, which is not supported (see here).

One option would be to instead return a fixed size array e.g.

function getTrackDetailsNew(bytes32 _iswc) public constant returns(bytes32[10] isrc) {  
    ...
}

However, this is somewhat limiting as you are stuck with a fixed size array.

An alternative could be to keep the dynamic isrc array in a public state variable which could be queried after the function has been executed.

Harry Wright
  • 1,171
  • 9
  • 19
2

This code worked for me.

function getTrackDetailsByIswc(bytes32 _iswc) public constant returns(bytes32[]) {

    getCount(_iswc);
    bytes32[] memory isrc = new bytes32[](c);

    bytes32 tempiswc;
    uint count = KeyArray.length;
    uint j;

    for (uint8 i=0; i < count; i++) {
        tempiswc = track[KeyArray[i]].iswc;
        if (tempiswc == _iswc) {
            isrc[j] = KeyArray[i];
            j++;
        }
    }
    return isrc;
} 
sruthi23
  • 361
  • 4
  • 15
1

In case you need this data returned off-chain (not in a contract to contract call) you could simply iterate through the entries of a public array.

n1cK
  • 3,378
  • 2
  • 12
  • 18