简体   繁体   中英

Arduino array memory usage

If I declare an array in the global scope, it uses up memory to store it. However, if I declare an array (I am using two types, one is a char array, while the other is an int array) inside a function (such as setup() ) will the memory be freed automatically once the array goes out of scope?

I believe this happens for some variables such as int or byte. I just wanted to know if this applies to arrays as well.

Also, since I read that for programs containing lots of strings, it is best to store them in program space, does a call such as

lcd.print("Hello")

still use up the memory for the "Hello" string after the function ends (assuming that the print function does not store it someplace else)?

To the second question:

The F() macro will store strings in the progmen instead of using RAM , so you do not have this problem anymore:

lcd.print(F("Hello"));

As to your 1st question: Yes. All variables declared inside a function are only valid inside until the function returns and are released automatically then. This has some implications:

  1. You must not use a pointer to a locally declared variable after the variable went out of scope, for instance, after the function returned. ( Don't return a pointer to a local array from your function!) - It is however perfecly legal to pass that pointer to other functions when calling them from within the declaring block/function.

  2. Local variables are stored on the local stack so that there needs to be enough room left for the stack to grow by the corresponding number of bytes when the function is called.

  3. The amount of memory used by those variables is not accounted for in the calculation of "used" RAM at compile time .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM