Solidity-018 StorageToMemoryReferenceTypeAssignment

发布时间:2024年01月19日

// SPDX-License-Identifier: MIT

// This line specifies the license under which this code is released, in this case, the MIT License.

pragma solidity ^0.8.9;

// This line specifies the compiler version this code is written for, here it's version 0.8.9 of Solidity.

contract StorageToMemoryReferenceTypeAssignment {

? ? // A Solidity contract named StorageToMemoryReferenceTypeAssignment.

? ? // This contract demonstrates how storage and memory data locations interact.

? ? uint[2] stateArray3 = [uint(1), 2];

? ? // Declares a state variable 'stateArray3' which is an array of two unsigned integers.

? ? // It's stored in contract storage and initialized with the values 1 and 2.

? ? function getUInt() public returns (uint) {

? ? ? ? // A public function named getUInt. It returns an unsigned integer.

? ? ? ? uint[2] memory localArray = stateArray3;

? ? ? ? // Declares a memory array 'localArray' and initializes it with the current values of 'stateArray3'.

? ? ? ? // Since 'localArray' is stored in memory, it's a separate copy from 'stateArray3'.

? ? ? ? stateArray3[1] = 5;

? ? ? ? // Modifies the second element of 'stateArray3' to 5.

? ? ? ? // This change does not affect 'localArray' as they are separate copies.

? ? ? ? return localArray[1]; // returns 2

? ? ? ? // Returns the second element of 'localArray'.

? ? ? ? // Even though 'stateArray3' was modified, 'localArray' still holds the original values.

? ? ? ? // Thus, this returns 2, the original second value of 'stateArray3'.

? ? }

}

//Deploy screenshow:

文章来源:https://blog.csdn.net/m0_61408373/article/details/135692643
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。