我正在尝试测试此简单合同以从数组中删除地址,但我一直收到此“无效操作码”错误。
contract C {
address[] addrList;
function addAddr(address addr) public{
addrList.push(addr);
}
function deleteAddr(address addr)public {
for(uint256 i = 0; i < addrList.length; i++) {
if(addr == addrList[i]) {
for(uint256 j = i; j < addrList.length; j++)
addrList[j] = addrList[j + 1];
delete addrList[addrList.length - 1];
addrList.length--; // <== This gives Error: Expression has to be an lvalue.
}
答案 0 :(得分:1)
该错误即将到来,因为您正在将变量j
从i
迭代到addrList.length-1
。这会使addrList[j+1]
超出索引。
您需要将j
从i
迭代到addrList.length-2
。可以通过将条件更新为j < addrList.length-1
来实现。
pragma solidity ^0.5.3;
contract C {
address[] addrList;
function addAddr(address addr) public{
addrList.push(addr);
}
function deleteAddr(address addr) public {
for(uint256 i = 0; i < addrList.length; i++) {
if(addr == addrList[i]) {
for(uint256 j = i; j < addrList.length-1; j++) {
addrList[j] = addrList[j + 1];
}
//delete addrList[addrList.length - 1];
addrList.length--;
}
}
}
function returnList() view public returns (address[] memory) {
return addrList;
}
}
此外,您也不需要使用delete步骤,因为编译器会自行清理内存插槽。