Solidity
就記憶體佈局而言,數組的長度在哪裡?
例如,給定以下情況:
uint[3] memory arr; uint[] memory arr = new uint[](3);
假設我嘗試
arr
從一個assembly
塊內訪問(mload
例如,使用 )。位置的值在哪裡(相對於
arr
)arr.length
,條目在哪裡?謝謝!
好的,我跑了一個簡單的測試,發現在動態數組中,數組的長度位於相對於數組開頭的前 32 個字節處:
智能合約:
pragma solidity 0.4.25; contract MyContract { function read1() external pure returns (uint a, uint b, uint c) { uint[3] memory arr; arr[0] = 111; arr[1] = 222; arr[2] = 333; assembly { a := mload(add(arr, 0)) b := mload(add(arr, 32)) c := mload(add(arr, 64)) } } function read2() external pure returns (uint a, uint b, uint c) { uint[] memory arr = new uint[](3); arr[0] = 444; arr[1] = 555; arr[2] = 666; assembly { a := mload(add(arr, 0)) b := mload(add(arr, 32)) c := mload(add(arr, 64)) } } }
松露測試:
contract("MyContract", function(accounts) { it("test", async function() { const myContract = await artifacts.require("MyContract").new(); await test(myContract.read1); await test(myContract.read2); }); async function test(func) { const [a, b, c] = await func(); console.log(a.toFixed(), b.toFixed(), c.toFixed()); } });
列印:
111 222 333 (this is for the `uint[3] memory arr`) 3 444 555 (this is for the `uint[] memory arr = new uint[](3)`)