【问题标题】:How to store a string in a Solidity contract?如何在 Solidity 合约中存储字符串?
【发布时间】:2018-10-24 19:59:34
【问题描述】:

我正在创建一个存储字符串数组的合约。

我正在使用 truffle 和 ganache-cli 测试合同。当我使用任何字符串调用方法putData() 时,它会给出错误Error: VM Exception while processing transaction: invalid opcode

代码如下:

pragma solidity ^0.4.24;

contract DataContract {

    address public owner;
    uint public index = 0;
    string[] public data;

    // Constructor
    constructor() public {
        owner = msg.sender;
    }

    function putData(string _d) public {
        data[index] = _d;
        index = index + 1;
    }

}

我怎样才能做到这一点?

【问题讨论】:

    标签: arrays string solidity truffle


    【解决方案1】:

    您正在写超出数组的末尾。 (长度为 0,所以没有空间存储任何东西。)

    完全删除index 的东西并使用push,这将为您增加数组的大小:

    function putData(string  _d) public {
        data.push(_d);
    }
    

    【讨论】:

      猜你喜欢
      • 2022-07-11
      • 2021-08-22
      • 1970-01-01
      • 2021-12-26
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多