Solidity

Solidity 返回單位顯示錯誤無效操作碼

  • October 20, 2022

我使用 add 函式將數據添加到映射數組。我想用函式 get_all 顯示數組中的所有數據,就像這段程式碼一樣。

struct Client{
       uint x;
   }

   mapping(uint => Client[]) client;

   function add(uint id, uint _x) public {
       client[id].push(Client(_x));
   }

   function get_all(uint id) public view returns(uint[] memory){

       uint[] memory lastItems;
       for(uint i=0;i<client[id].length;i++){

               lastItems[i] = client[id][client[id].length-i-1].x;
          
       }
       return lastItems;
   }

我把樣本數據放在這樣的函式中。

10,11
10,12

當我通過將 id 設置為 10 執行函式 get_all 時,它會顯示這樣的錯誤。

[call]
from: 0x5B3...eddC4
to: Test.get_last(uint256)
data: 0x84f...0000a
from    0x5B3...eddC4
to  Test.get_last(uint256) 0x7b9...b6AcE
execution cost  3000000 gas (Cost only applies when called by a contract)
input   0x84f...0000a
decoded input   {
   "uint256 id": "10"
}
decoded output  {
   "0": "uint256[]: "
}
logs    []

call to Test.get_last errored: VM error: invalid opcode.

invalid opcode
   
   The execution might have thrown.

Debug the transaction to get more information.

如何顯示映射數組中的所有數據?

這樣做的原因是您試圖在沒有大小的數組的索引處設置值:

uint[] memory lastItems;

如果要直接使用i索引推送,請嘗試給它固定長度,如下所示:

Client[] storage clients = client[id];
uint[] memory lastItems = new uint[](clients.length);

它應該工作:)

引用自:https://ethereum.stackexchange.com/questions/137840