如何在 Solidity 合约中存储字符串?
How to store a string in a Solidity contract?
我正在创建一个存储字符串数组的合约。
我正在用 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;
}
}
我怎样才能完成这项工作?
您正在写入数组末尾。 (它的长度为 0,所以没有空间存储任何东西。)
只需完全删除 index
内容并使用 push
,这将为您增加数组的大小:
function putData(string _d) public {
data.push(_d);
}
我正在创建一个存储字符串数组的合约。
我正在用 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;
}
}
我怎样才能完成这项工作?
您正在写入数组末尾。 (它的长度为 0,所以没有空间存储任何东西。)
只需完全删除 index
内容并使用 push
,这将为您增加数组的大小:
function putData(string _d) public {
data.push(_d);
}