// @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列表,但是它不会筛选通过,但会返回所有可用的房屋。 当我改用String utils时,没有任何改变。
这是整个代码:
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;
}
}
答案 0 :(得分:2)
给您带来麻烦的部分是uint[] results;
行。默认情况下,声明为局部变量的数组引用storage
内存。在Solidity docs的“什么是内存关键字”部分中:
根据所涉及的变量类型,存储位置有默认值:
- 状态变量始终处于存储状态
- 默认情况下,函数参数在内存中
默认情况下,- 结构,数组或映射类型的局部变量引用存储
- 值类型的局部变量(即既不是数组,也不是结构或映射)存储在堆栈中
结果是您引用的是合同的第一个存储插槽,恰好是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;
}