I would have thought an array of structs would have been the natural choice here but assuming there's a reason you want an array of contracts I stuck with your example.
No issue pushing the contracts into a dynamic array, but needed to define a fixed size array to assign by element number. The element has to exist before it can be assigned.
No problem assigning by element number once the element exists even with the dynamic array.
e.g.
string[] bigDogs;
bigDogs.push("fido");
bigDogs.push("woof");
bigDogs[2] = ("bark"); // will error
bigDogs.push("");
bigDogs[2] = ("bark"); // ok now
pragma solidity ^0.8.14;
import "hardhat/console.sol";
contract Dog {
string name;
constructor(string memory _name){
name = _name;
console.log("conatract deployed with dog name", name);
}
}
contract Human {
Dog[] bigDogs;
Dog[3] smlDogs; // or Dog[] smlDogs = new Dog[](3);
uint currDogs = 0;
function addSmlDogs() public {
smlDogs[0] = new Dog("pooch");
smlDogs[1] = new Dog("pinky");
smlDogs[2] = new Dog("puff");
}
function addBigDogs() public {
bigDogs.push(new Dog("fido"));
bigDogs.push(new Dog("woof"));
bigDogs.push(new Dog("bark"));
}
function showDogs() external view {
for(uint i; i < smlDogs.length; ++i ) {
console.log(address(smlDogs[i]));
}
for(uint i; i < bigDogs.length; ++i ) {
console.log(address(bigDogs[i]));
}
}
}
output
[vm]from: 0x5B3...eddC4to: Human.addBigDogs() 0x7FD...9Bd66value: 0 weidata: 0xa06...68f30logs: 0hash: 0x254...18c37
console.log:
conatract deployed with dog name fido
conatract deployed with dog name woof
conatract deployed with dog name bark
transact to Human.addSmlDogs pending ...
[vm]from: 0x5B3...eddC4to: Human.addSmlDogs() 0x7FD...9Bd66value: 0 weidata: 0x9cb...a3d07logs: 0hash: 0x9c3...39212
console.log:
conatract deployed with dog name pooch
conatract deployed with dog name pinky
conatract deployed with dog name puff
call to Human.showDogs
CALL
[call]from: 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4to: Human.showDogs()data: 0xdbd...5503b
console.log:
0xFE6310B4745c4a9b9977A5b06B2e3834360b3Cfd
0x61367B4487FA6364FAc15965068d9629A2442efE
0x70D6ED8b901Cc7c067B6B054b287b3929aF6A0F4
0x5416e367FbA90B0f3E05b4e20Abef8F344B240c2
0x0484d676FCFd6350C28a6Fc58F2D92531D90ea13
0x2c31f122D5FA5A44cE717fd6E8718F7F7e040Bf2