// @param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
// @return _id - list of ids for homes
function listHomesByAddress(string _physicalAddress) public returns(uint [] _id ) {
uint [] results;
for(uint i = 0 ; i<homes.length; i++) {
if(keccak256(homes[i].physicalAddress) == keccak256(_physicalAddress) && homes[i].available == true) {
results.push(homes[i].id);
}
}
return results;
}
结果应该是与输入的物理地址匹配的 id 列表,但它不会过滤,而是返回所有可用的家庭。 当我更改为使用字符串时,没有任何变化。
这是整个代码:
pragma solidity ^0.4.0;
import "browser/StringUtils.sol";
// @title HomeListing
contract HomeListing {
struct Home {
uint id;
string physicalAddress;
bool available;
}
Home[] public homes;
mapping (address => Home) hostToHome;
event HomeEvent(uint _id);
event Test(uint length);
constructor() {
}
// @param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
function addHome(string _physicalAddress) public {
uint _id = uint(keccak256(_physicalAddress, msg.sender));
homes.push(Home(_id, _physicalAddress, true));
}
// @param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
// @return _id - list of ids for homes
function listHomesByAddress(string _physicalAddress) public returns(uint [] _id ) {
uint [] results;
for(uint i = 0 ; i<homes.length; i++) {
string location = homes[i].physicalAddress;
if(StringUtils.equal(location,_physicalAddress )) {
results.push(homes[i].id);
}
}
return results;
}
}
给你带来麻烦的部分是行uint[] results;
。默认情况下,声明为局部变量的数组引用内存storage
。从 Solidity 文档的"什么是内存关键字"部分:
存储位置有默认值,具体取决于它涉及的变量类型:
- 状态变量始终在存储中
- 默认情况下,函数参数位于内存中
- 默认情况下,结构、数组或映射类型引用存储的局部变量
- 值类型的局部变量(即既不是数组,也不是结构或映射(存储在堆栈中
结果是你引用了合约的第一个存储槽,恰好是Home[] public homes
。这就是您取回整个阵列的原因。
要解决此问题,您需要使用memory
数组。但是,您还有一个额外的问题,即您无法在 Solidity 中使用动态内存阵列。解决方法是确定结果大小限制并静态声明数组。
示例(仅限 10 个结果(:
function listHomesByAddress(string _physicalAddress) public view returns(uint[10]) {
uint [10] memory results;
uint j = 0;
for(uint i = 0 ; i<homes.length && j < 10; i++) {
if(keccak256(homes[i].physicalAddress) == keccak256(_physicalAddress) && homes[i].available == true) {
results[j++] = homes[i].id;
}
}
return results;
}