0

I have a couple of questions regarding local variables and creating structs and arrays. As I understand they can be stored in memory and in storage. If they defined as state variables they will be stored in the blockchain. I found that I can create memory array as a local variable using new clause and specifying the array size.But I cannot find a way to declare array(or struct) as a storage array inside of the function.Is it possible to do? The only thing I've understood I can create a storage pointer to already existed array defined as the state variable.That it's another question why do we need some, if by changing it we change the original array? And one more question about the following statement from the documentation: Local Variables of structs, array are always stored in storage by default. Could you give an example of this?

//local variables testing
    uint[] public some_arr;



    function test_local_var() public {
        some_arr.push(1);
        some_arr.push(2);
        some_arr.push(3);
        uint[] storage new_arr = some_arr;//Why do we need to create a storage pointer to array if by changing it we change an original array 
        new_arr[0]=3232;
        new_arr.push(4);
        uint[] memory new_arr2 = new uint[](7); //how to create storage array inside of a function? I found the way how to create memory arrays

    } 

Thank you in advance!

1 Answer 1

0

how to create storage array inside of a function?

You cannot do that, creating new storage slots inside of a function isnt possible at all. (well, you could do it in assembly, but you could manage that slot only by reading and writing to it via assembly, you wouldnt be able to name it and access it with solidity afterwards at all).

Why do we need to create a storage pointer to array if by changing it we change an original array

Well, we don't. It's just meant as a shortcut to write cleaner code. Let's take this storage layout as example.

struct SomeStruct{
uint256 a;
uint256[] b;
//...
}
mapping(address => mapping(address => SomeStruct[]) someAnnoyingToAccessMapping;

Now let's say i want to modify b inside a struct inside my annoying mapping. I could spend 2 hours rewriting

someAnnoyingToAccessMapping[someAddr1][someAddr2].b[...];

over and over again, or i could just write

uint256[] storage toModify = someAnnoyingToAccessMapping[address][address].b;

once, and then access it directly using toModify without having to type the whole thing again everytime

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.