简体   繁体   English

Arduino阵列内存使用情况

[英]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? 但是,如果我在函数(例如setup() )中声明一个数组(我使用两种类型,一种是char数组,另一种是int数组),则一旦该数组退出数组,该内存就会自动释放范围?

I believe this happens for some variables such as int or byte. 我相信这对于某些变量(例如int或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)? 函数结束后是否仍然用完“ Hello”字符串的内存(假设打印函数未将其存储在其他地方)?

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: F()宏会将字符串存储在progmen中,而不是使用RAM ,因此您不再遇到此问题:

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. 不要返回一个指针从函数的局部阵!) -然而perfecly法律从声明块/函数调用它们时该指针传递给其他的功能。

  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 . 这些变量使用的内存量 在编译时计算“已用” RAM 时考虑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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