6

Here is the code:

pragma solidity^0.4.16; contract Test { struct SomeData { address[] users; } address[] nullArray; mapping(uint => SomeData) SomeDataList; function insertData(uint number) { SomeDataList[number] = SomeData({ users : nullArray }); SomeDataList[number].users.push(msg.sender); } } 

In insertData function I initialize a new structure and assign nullArray to users field (users now store a copy of nullArray or a pointer to it?). After that, I push some data to this structure and I'm not sure whether the global variable nullArray will be affected or not.

1
  • @AchalaDissanayake Sorry, just misclicked because of browser lag)) answer is great Commented Jul 25, 2018 at 14:46

2 Answers 2

2

users now store a copy of nullArray or a pointer to it?

It will create an independent copy. As I understand since both nullArray and SomeDataList are state variables there will be two independent copies.

It's mentioned in the solidity docs here that,

assignments between storage and memory and also to a state variable (even from other state variables) always create an independent copy.

hence,

I push some data to this structure and I'm not sure whether the global variable nullArray will be affected or not

nullArray will not be affected.

UPDATE

I tried your code with some additional functions in Remix-IDE as follow,

pragma solidity^0.4.16; contract Test { struct SomeData { address[] users; } address[] nullArray; mapping(uint => SomeData) SomeDataList; function insertData(uint number) { SomeDataList[number] = SomeData({ users : nullArray }); SomeDataList[number].users.push(msg.sender); } function getusers(uint number) constant returns(address []){ return SomeDataList[number].users; } function getNullArray() constant returns(address[]){ return nullArray; } function pushNullArray(address addr){ nullArray.push(addr); } } 

And nullArray and SomeDataList acted as two different variables. Here are the function call results after calling pushNullArray(address addr) and insertData(uint number) with some arbitrary values.

enter image description here

They were not the same.

Hope this helps!

2

It creates a copy. Even though nullArray & users here are storage reference types, assignment to state variables always does a copy.

https://docs.soliditylang.org/en/v0.8.13/types.html#data-location-and-assignment-behaviour

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.