使用new关键字在内存中建立可变长度数组,相对于stroge中的数组,它不能使用length改变长度
pragma solidity ^0.4.16;
contract C {
functionf(uint len) public pure {
uint[] memory a = new uint[] (7);
bytes memory b = new bytes (len);
// a.length == 7, b.length == len
a[6] = 8;
}
}
数组常量
数组常量只能通过表达式声明,不能批派到变量
pragma solidity ^0.4.16;
contract C {
functionf() public pure {
g([uint(1), 2, 3]);
}
functiong(uint[3] _data) public pure {
// ...
}
}
以下是错误的
pragma solidity ^0.4.0;
contract C {
functionf() public {
// The next line creates a type error because uint[3] memory cannot be converted to uint[] memory.
uint[] x = [uint(1), 3, 4];
}
}
完整例子
pragma solidity ^0.4.16;
contract ArrayContract {
uint[2**20] m_aLotOfIntegers;
// Note that the following is not a pair of dynamic arrays but a// dynamic array of pairs (i.e. of fixed size arrays of length two).
bool[2][] m_pairsOfFlags;
// newPairs is stored in memory - the default for function arguments
2functionsetAllFlagPairs(bool[2][] newPairs) public {
// assignment to a storage array replaces the complete array
m_pairsOfFlags = newPairs;
}
functionsetFlagPair(uint index, bool flagA, bool flagB) public {
// access to a non-existing index will throw an exception
m_pairsOfFlags[index][0] = flagA;
m_pairsOfFlags[index][1] = flagB;
}
functionchangeFlagArraySize(uint newSize) public {
// if the new size is smaller, removed array elements will be cleared
m_pairsOfFlags.length = newSize;
}
functionclear() public {
// these clear the arrays completelydelete m_pairsOfFlags;
delete m_aLotOfIntegers;
// identical effect here
m_pairsOfFlags.length = 0;
}
bytes m_byteData;
functionbyteArrays(bytes data) public {
// byte arrays ("bytes") are different as they are stored without padding,// but can be treated identical to "uint8[]"
m_byteData = data;
m_byteData.length += 7;
m_byteData[3] = byte(8);
delete m_byteData[2];
}
functionaddFlag(bool[2] flag) public returns (uint) {
return m_pairsOfFlags.push(flag);
}
functioncreateMemoryArray(uint size) public pure returns (bytes) {
// Dynamic memory arrays are created using `new`:
uint[2][] memory arrayOfPairs = new uint[2][](size);
// Create a dynamic byte array:
bytes memory b = newbytes(200);
for (uint i = 0; i < b.length; i++)
b[i] = byte(i);
return b;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类