0

This must be silly question but as a new learner i am trying to understand array in solidity and run this code in remix, compiled and deployed the contract on ropsten platform. I want to see the array value which i am returning in the end.But calling that getA function gives nothing. I'm doing the transaction in metamask.

pragma solidity 0.5.1;

contract SolArray{
    uint[] a;

    function getA() constant returns  (uint[] memory){

        a.push(123);
        return a;
    }


}
1

I don't see how that would compile because constant is deprecated in 0.5.1.

In any case, remove constant because "read-only" is inappropriate if you want the storage state to change. In case that sounds cryptic, have a look over here: https://blog.b9lab.com/calls-vs-transactions-in-ethereum-smart-contracts-62d6b17d0bc2 and When to use "View" and "Pure" in place of "Constant"

Instead of your array, you'll get a transaction hash and you'll want another function to return the array. You can do that with public.

Try it like this:

pragma solidity 0.5.1;

contract SolArray {

    uint[] public a;

    function pushA(uint value) public {
        a.push(value);
    }
}

You will see that function a() asks for a row/index to return. This is the scalable pattern that will have a consistent gas cost at any scale. A client would iterate the array to get all rows.

To make it more like your original code, you could add a function to return the whole array, with the warning: This is not scalable. It will cease working when the gas cost to return the whole thing exceeds the block gasLimit.

pragma solidity 0.5.1;

contract SolArray {

    uint[] public a;

    function pushA(uint value) public {
        a.push(value);
    }

    function getAll() public view returns(uint[] memory) {
        return a;
    }
}

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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