为什么我不能在实心中返回动态数组? [英] Why can't I return dynamic array in Solidity?
本文介绍了为什么我不能在实心中返回动态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过声明一个数组并在for循环中将其推送到该数组来返回地址列表。但是,当我尝试返回动态数组时,实心度就不一样了。
function listMyPromises() public returns(uint256[] memory ){ //lists all my past promises
uint256[] memory List;
for(uint i=0; i<table.length; i++){
if(table[i].userAddress==msg.sender){
List.push(uint256(table[i].friendAddress));
}
}
return List;
}
坚固性不允许我返回数组来声明
TypeError:对于函数中的返回参数,数据位置必须是";Memory";或";alldata";,但未给出任何值。 但是,当我在返回参数中添加内存时,我得到错误: 类型错误:uint256[]内存中存储空间外的成员推送不可用
我不知道该怎么办。
推荐答案
固态不允许调整内存阵列的大小(例如,使用.push()
)。
您需要事先计算大小,然后创建固定大小的内存数组。
来源:docs
因此结果可能如下所示
function listMyPromises() public returns(uint256[] memory ){ //lists all my past promises
uint256 count = getCount();
uint256[] memory List = new uint256[](count);
uint256 j;
for (uint i = 0; i < table.length; i++) {
if(table[i].userAddress==msg.sender){
List[j] = uint256(table[i].friendAddress);
j++;
}
}
return List;
}
function getCount() internal view returns (uint) {
uint count;
for (uint i = 0; i < table.length; i++) {
if (table[i].userAddress == msg.sender) {
count++;
}
}
return count;
}
根据
table[i]
结构中包装的数据类型,您可能还会遇到另一个错误。friendAddress
提示它是address
类型,但无法转换为uint256
。
这篇关于为什么我不能在实心中返回动态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文