0

function addCropDetails //only farmer can call ( uint _cropType, //string memory _cropName, uint _quantity, string memory _location ) public { require ( owner != msg.sender , "owner cant add crop details" ); //u r not registered yet require (farmers[msg.sender].isRegistered == true, "You are not registered yet or you are not farmer"); require ( allPricesSet==true , "gov isnt initialized prices yet" ); require ( setProfitPercent == true , "gov isnt initialized profit rates yet" ); require ( _cropType < arraySize && _cropType >= 0 , "invalid crop type");

    uint cropPr = cropTypes[_cropType]; //fetched cropPrice by cropType (by gov)
    
    cropCounter++;
    Crop memory crop ;
    crop.cropId=cropCounter;
    //adding crop type to cropType
    crop.cropType = _cropType;        
    crop.farmer_quantity=_quantity;
    crop.location=_location;
    crop.farmerAddrs = payable(msg.sender);
    crop.cropPrice = cropPr;
    crop.isAdded=true;
    crops[cropCounter] = crop;      //here i passed instance to mapping
    

//in below lines i tried to add instance to array in many ways but not even one is working //function is working only after commenting this.

    //fCropArray[cropCounter] = crops[cropCounter];    
    //fCropArray[cropCounter]=crop;
    //addCropToArray(crops[cropCounter]);
    
    emit cropAdded();
}

1 Answer 1

1
cropCounter++;
...
crops[cropCounter] = crop;

If this is a dynamic array and you are attempting to implicitly extend it (as I assume is the case), then you are stepping out of bounds. It fails because cropCounter is not lessThanOrEqual to crops.length.

Try

crops.push(crop);

That explicitly appends an element to the end and increases the array length.

Hope it helps.

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.