【问题标题】:Solidity/Remix: Why does this function fail on assignment of an array member?Solidity/Remix:为什么这个函数在分配数组成员时失败?
【发布时间】:2021-08-28 18:25:32
【问题描述】:

我编写了这个简单的函数来获取字符串数组并消除重复项,但它使用提供的参数["a","b","c"] 进行还原。我认为它可能与 equals 函数(比较两个字符串)有关,但它本身运行良好。在调试器中,它挂在如下所示的赋值语句上,该语句位于equals 函数调用之前。

任何想法表示赞赏。

pragma solidity >=0.7.0 <0.9.0;
contract Tester  {
    
    function dedupeKeys(string[] memory keys) public pure returns(string[] memory) {
       
        string[] memory deduped;
         if (keys.length == 0) return deduped;  
        bool found;
        string memory key;
        key = keys[0];
        deduped[0] = key;   //REMIX DEBUGGER HANGS HERE.            
        for(uint i=1; i<keys.length; i++) {
            found = false;
            key = keys[i];
            for(uint j=0; j<keys.length; j++) {
                if(equal(deduped[j], key)) {
                   found=true; 
                }
            }
            if (!found) {
                deduped[deduped.length]=key;
            }
        }
        return deduped;
    }
    
    function equal(string memory _base, string memory _value)
        internal
        pure
        returns (bool) {
        bytes memory _baseBytes = bytes(_base);
        bytes memory _valueBytes = bytes(_value);

        if (_baseBytes.length != _valueBytes.length) {
            return false;
        }

        for (uint i = 0; i < _baseBytes.length; i++) {
            if (_baseBytes[i] != _valueBytes[i]) {
                return false;
            }
        }

        return true;
    }

}

【问题讨论】:

    标签: solidity remix


    【解决方案1】:

    您正在尝试访问超出范围的数组索引。

    此行创建包含 0 个项目的数组:

    string[] memory deduped;
    

    在这里,您正在尝试访问 第一项(索引 0):

    deduped[0] = key;   //REMIX DEBUGGER HANGS HERE.  
    

    在当前的 Solidity 版本 (0.8.x) 中,无法调整内存阵列的大小。所以你需要用正确的尺寸创建它,并事先计算好尺寸。代码示例见this answer

    【讨论】:

    • 谢谢彼得。很惊讶它没有触发编译器错误。没有意识到你不能在内存中拥有动态数组。但我想这就是为什么 .push 也不适用于 memroy 数组的原因。
    • @GGizmos 没错,push() 仅在存储阵列上可用 - 而不是内存。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 2023-03-08
    • 2018-09-19
    相关资源
    最近更新 更多