'How to push onto a dynamic sized Array within a function with Solidity?
How can I push a value into an dynamic sized array within a function?
I have a function which builds an array dynamically to use this as a function argument afterwards:
function autoMintBatch(...) {
uint32[] xList;
uint32[] yList;
// ... y is declared properly ...
yList.push(y);
for (uint256 i = 0; i < idList.length; i++) {
xList.push(x++);
}
}
I get the following compilation error:
TypeError: Member "push" is not available in uint32[] memory outside of storage.
But when I change the variable declaration to storage like:
uint32[] storage xList;
another error appears:
TypeError: This variable is of storage pointer type and can be accessed without prior assignment, which would lead to undefined behaviour.
Is there any way to build an array dynamically within a function?
Solution 1:[1]
Assign the result of "x++" in a variable inside the function and then try to push the variable inside the array. Remember to create a state variable for the array. This worked for me
Item[] public items;
event MarketItem(
bytes32 title,
uint8 price,
bool sold,
bool published,
address owner
);
mapping(address => Item) public itemToOwner;
function addItem(bytes32 _title, uint8 _price) public {
Item memory newItem = Item({
title: _title,
price: _price,
sold: false,
published: true,
owner: msg.sender
});
items.push(newItem);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RainbowWzrd |
