1

I study array in solidity ,when i write dynamic two dimensional and add value to array i get error why? and how to add value to array

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.1 <0.9.0;
contract myarray{
   
    uint[6] ipadPrice=[1000,2000,3000,4000,5000,1000];  // fixed size integer array with 6 elements
    uint[]  macPrice=[1100,2100,3100]; // dynamic array
    uint[2] ipadPricePro=[1500,2000]; // one dimensional fixed size array
    uint[] macPricePro=[2000,2500,3000]; //one dimensional dynamic array
    uint[][]ipadAirPrice=[1200,1400,1600,1800][8,6,8,4];

    
}

2 Answers 2

1

This is how you can do it:

contract myarray {

    uint[][] ipadAirPrice = [[uint(1200),1400,1600,1800],[uint(8),6,8,4]];

    function addElement(uint256 subArrayIndex, uint256 element) public {
        ipadAirPrice[subArrayIndex].push(element);
    }

    function getElements() public view returns(uint[][] memory) {
        return ipadAirPrice;
    }
    
}

Notice how it's necessary to manually cast the first elements of the sub-arrays to a common type, because Solidity tries to use the small numbers you have in the array (8, 6, 8 4) as uint8 and the big numbers (1200, 1400, etc) as the next type that can hold them, which would be uint16. Since uint8 and uint16 are not compatible, you need to cast at least the first element of each sub-array to a common element so you let Solidity know what is the type of each of those sub-elements.

Solidity compiler is not yet smart enough to handle that. Maybe in the future, it will.

1
  • Would it be sufficient to declare the array as uint256[][]? Commented Sep 14, 2022 at 16:43
0
uint[][]ipadAirPrice=[1200,1400,1600,1800][8,6,8,4]; 

should be:

uint[][]ipadAirPrice=[[1200,1400,1600,1800],[8,6,8,4]];
0

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.