1

Consider this code.

function getDoctorsList(uint[] memory _docIds) public view returns (doctor[] memory) {
    doctor[] memory _doctors;
    for(uint i = 0; i < _docIds.length; i++) {
        _doctors[i] = doctors[_docIds[i]];
    }
    return _doctors;
}

Here I am using an array of id's of a mapping and store the appropriate struct instance into a dynamic array of struct instances. But I can not execute this function. It is saying that:

call to DogChain.getDoctorsList errored: VM error: invalid opcode. invalid opcode The execution might have thrown. Debug the transaction to get more information.

Previously, I tried pushing each items. But compiler says, it is not possible. can anyone help me with this?

2

You need to initialize the dynamic array to the required length:

doctor[] memory _doctors = new doctor[](_docIds.length);

More generally, there are 4 types of arrays:

  1. Inside functions, a static array in memory , e.g., type[3] memory arr;
  2. Inside functions, a dynamic array in memory , e.g., type[] memory arr = new type[](3);
  3. Outside functions, a static array in storage, e.g., type[3] public arr;
  4. Outside functions, a dynamic array in storage, e.g., type[] public arr;

You can push/pop only to/from dynamic arrays in storage.

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.