为什么我无法在 Solidity 中返回动态数组?

Chi*_*pal 1 solidity remix

我试图通过声明一个数组并在 for 循环中推送到它来返回地址列表。然而,Solidity 不喜欢我尝试返回动态数组。

    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;
}
Run Code Online (Sandbox Code Playgroud)

Solidity 不允许我返回一个数组,说明

类型错误:函数中返回参数的数据位置必须是“内存”或“calldata”,但没有给出。但是,当我在返回参数中添加内存时,出现错误: TypeError: Member "push" is not available in uint256[] memory Outside of storage

我不知道该怎么办。

Pet*_*jda 6

Solidity 不允许调整.push()内存阵列的大小(例如通过使用 )。

需要预先计算好大小,然后创建一个固定大小的内存数组。

来源:文档


所以结果可能看起来像这样

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;
}
Run Code Online (Sandbox Code Playgroud)

根据table[i]结构中包装的数据类型,您可能还会遇到另一个错误。表明friendAddress它是一种类型address,但无法转换为uint256