In some contexts, the keyword memory
seems quite similar to a reference type in C++, where it gives an alias to a variable (see method 1 below). It confuses me when it's used to specify the return value data location.
I tested my code in Remix, supposedly both method 1 and 2 would return same values. However method 2 returns an array of all zeros. Could somebody tell me what's happening here?
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.8;
contract Test3 {
struct A {
uint256 a;
uint256 b;
}
// method 1: assigning values in the loop
function LoopThrough() external pure returns (A[] memory _A) {
_A = new A[](5);
for (uint256 i = 0; i< 5; ++i) {
A memory _memoryA = _A[i];
_memoryA.a = 123;
_memoryA.b = 456;
}
}
// method 2: assigning value in another function
function LoopThrough2() external pure returns (A[] memory _A) {
_A = new A[](5);
for (uint256 i = 0; i< 5; ++i) {
A memory _memoryA = _A[i];
_memoryA = _internalReturn();
}
}
// helper function
function _internalReturn() internal pure returns (A memory _a) {
_a.a = 123;
_a.b = 456;
}
}
Edit 1
In C++, method 2 seems to be working. Here's a link to C++ code on Compiler Explorer.