3

What is the best practice for concatenting arrays in Solidity?

I have this (which compiles):

contract Concatenator {
    address[]  Accounts1;
    function ConcatenateArrays(address[] Accounts2){
        uint i = 0;
        while (i++ < Accounts2.length) {
            Accounts1.push(Accounts2[i]);
        }
    } 
}

I have a feeling that there might be a better way of doing it, however. Hence this question.

Also, I noticed that, if I pass the 2 arrays to the function, I get a memory error. Why can't I pass the two arrays directly to the fucntion?

2

The code in the question runs Out of Gas because i should be incremented after Accounts1.push(Accounts2[i]); otherwise Accounts2[i] is an access out of bounds. Simpler to use a for loop:

contract Concatenator {
    address[]  Accounts1;
    function ConcatenateArrays(address[] Accounts2){
        for (uint i=0; i < Accounts2.length; i++) {
            Accounts1.push(Accounts2[i]);
        }
    } 
}

When passing 2 arrays to a function, you cannot resize either of them and you need to allocate and return a new array. Here is an example:

function ConcatenateArrays(address[] Accounts, address[] Accounts2) returns(address[]) {
    address[] memory returnArr = new address[](Accounts.length + Accounts2.length);

    uint i=0;
    for (; i < Accounts.length; i++) {
        returnArr[i] = Accounts[i];
    }

    uint j=0;
    while (j < Accounts.length) {
        returnArr[i++] = Accounts2[j++];
    }

    return returnArr;
} 

Note: memory and the returned dynamically-sized array is not accessible from another Solidity function (only in web3.js): see What are common pitfalls or limitations when coding in Solidity?

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.