0
pragma solidity ^0.8.9;

contract test{
    uint8[] memory lol;
}

I am new to solidity and i want to create dynamic array in memory but i always get this error Expected identifier but got 'memory'

Please help

3
  • You never define memory arrays in the contract storage. You have to remove the memory modifier and replace it with a visibility modifier, such as public, internal, or private. Oct 29, 2021 at 21:56
  • "You never define memory arrays in the contract storage" can you explain why please
    – нεx
    Oct 29, 2021 at 22:27
  • That's by design. Memory is allocated to function executions. Storage is allocated to the variables defined at the top of the contract. Oct 30, 2021 at 13:42

3 Answers 3

0

you just can't place a dynamic array in memory, it's not allowed

EDIT : nevermind, i missunderstood, this is wrong, sorry

1
  • put i when i moved the same variable in a function it worked
    – нεx
    Oct 30, 2021 at 10:37
0

I had a similar issue but I could solve it after digging into the code more

I declare and used the variable in function scope; Not at contract level or scope.

You could do it also in the contract's constructor and the code will compile.

delete the '-' line and add '+' lines

pragma solidity ^0.8.9;

  contract test {

 -  uint8[] memory lol;

 + constructor () {
 +    uint8[] memory lol;
 + }

}

Note that if you are not using 'lol' within the constructor, this initialization must be done within the function where you intend to use 'lol'

1
  • Declaring it inside the constructor will scope the variable only within the constructor function. OP wants to make a global variable, so the right answer would be to declare it as storage (default) and not memory. uint8[] lol;
    – pbsh
    Jan 30, 2022 at 14:19
0

The memory keyword indicates that the array is being stored in the temporary memory space that's only accessible during the execution of a function and is cleared once the function finishes executing.In Solidity, storage variables are used to persist data on the blockchain across function calls and transactions. You can't directly initialize a dynamic array like this in storage at the point of declaration. To create a dynamic array in storage, you usually need to split the declaration and initialization into two steps. Here's an example of how you can do that:

pragma solidity ^0.8.9;

contract test {
    uint8[] public lol;
    constructor() {
    lol.push(..);
    lol.push(..);
  }
}

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.