1

Hey I am trying to understand data location more it is stated in the docs that "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."

The problem is I tried testing it out with strings in code below it still returns the original value even after changing it later on. If I'm not wrong testing and newTesting should point to the same reference right? Since its memory to memory assignment.

function checkMax(string calldata _test) public view returns (string memory) {
    string memory testing = _test; 
    string memory newTesting = testing;
    newTesting = "changed bro!";
    assert(maxAmount == 100);
    return testing; // still returns the original _test parameter instead of "changed bro!"
}

1 Answer 1

0

This is because at the line:

newTesting = "changed bro!";

The reference for newTesting is being re-assigned and results in pointing to another memory location. Therefore, the change is only seen in newTesting and not in testing. I'm not sure if there exists a way to modify a string variable without re-assigning the reference.

It would be easier to demonstrate memory assignments with other reference types like structs as in the following example:

struct S {
      uint256 a;
      uint256 b;
}
...
function checkMax(S calldata _test) public pure returns (S memory) {
        S memory testing = _test; 
        S memory newTesting = testing;
        newTesting.a = 50;
        newTesting.b = 50;
        return testing; // returns tuple(uint256,uint256): 50,50
}
2
  • I thought strings are dynamic arrays in solidity hence making it reference type. Also, i have to specify data location for it which also indicates that it is a reference type correct me if im wrong Feb 26, 2022 at 18:19
  • @jmsandiegoo You are right, I need to update my answer. Feb 26, 2022 at 18:22

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.