4

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?

eth
  • 85,679
  • 53
  • 285
  • 406
Lee
  • 8,548
  • 6
  • 46
  • 80

1 Answers1

4

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?

eth
  • 85,679
  • 53
  • 285
  • 406
  • If the length of arrays are big then it is going to cost alot gas. – NinjaMAN Jul 20 '21 at 08:38
  • @NinjaMAN You're right and most answers are provided with the assumption that the developer has examined their design closely and they still need to do what they are asking. – eth Jul 30 '21 at 00:01