2

I have this simple code:

function restart() public returns (uint256[] ) {
    uint256[] memory result = new uint256[](5);
    result[0] = 10;
    uint256[] memory result1 = new uint256[](5);
    result1 = result;
    result1[1] = 20;
    return result;
}

The result final value is : {10,20}. But I wanted for it to just be {10}. Is there a way to copy an array without being a pointer? I basically just want to create a "local" copy of result. thank you

3
  • Can i see more of your code please? Thanks
    – Masoud jt
    May 9, 2020 at 15:33
  • this is the whole code! I just want to create a copy of an array without it being a pointer. I thought that the "memory" keyword would do just what i want. pragma solidity ^0.4.24; May 9, 2020 at 15:47
  • function restart() public returns (uint256[] ) { uint256[] memory result = new uint256[](5); result[0] = 10; uint256[] memory result1 = new uint256[](5); result1 = result; result1[1] = 20; return result; } May 9, 2020 at 15:51

2 Answers 2

1

You can copy element by element

function restart() public returns (uint256[] ) {
    uint256[] memory result = new uint256[](5);
    result[0] = 10;
    uint256[] memory result1 = new uint256[](5);

    for (uint i=0; i < 5; i += 1) {
        result1[i] = result[i];
    }

    result1[1] = 20;
    return result;
}
1

Well what you are doing is so strange for me. i think if you want to do this you can take out the result variable from the function memory and put it outside the function in storage.

uint256[] public result = new uint256[](5);
   
    function restart() public returns (uint256[] ) { 
        result[0] = 10; 
        uint256[] memory result1 = new uint256[](5); 
        result1 = result; 
        result1[1] = 20; 
        return result; 
        
    }

I think the reason for this is that when you make 2 memory variables in a function and assign one to another they both point out to the same location because they are both has been made inside a function and they're both local. So you can't do such a thing.

Solidity Docs

Assignments from memory to memory only create references. This means that changes to one memory variable are also visible in all other memory variables that refer to the same data.

I still wait for someone to approve or reject what i have said.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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