Forgive me if this is a dumb question. I created an array containing numeric values with a for loop. I had to declare the array locally, just before the loop, because the size of the array is determined by a user input from another part of the code. If I knew what the array size would have to be, I would have declared the array with the other global variables. Ultimately, I need to compare a sensor’s value (in another part of the code) against the values in this array. I’m getting the error code “‘array’ was not declared in this scope”. I realize why I’m getting the error: the array was previously declared locally, and now can’t be seen in this part of the code. Is there a work around for this? Can I simply store the list of array values in memory, and then access them later, in another part of the code, some how? Can I declare an array of an unknown variable size globally? I’ve been looking at using dynamic memory with malloc, but there are not many good tutorials on using this with arduino. Moreover, most of the stuff I’ve read on malloc and dynamic memory has stressed that it should be avoided if at all possible with arduino. I’m trying to do something that I assume would be simple and required in most programs, but I’m a novice and may be wrong. Does anyone know of a simple work around to having to use dynamic memory?
As long as you dimension the array only once, I don't see problems with malloc.
When the array becomes big, consider to use EEPROM for your table (caution: slower than RAM).
If you have room in RAM for the array why not just create it as a global array that is big enough for the biggest requirement.
What are you going to do with the space freed up if you release the memory?
...R
Or go to a chip with more SRAM - '1284P, 16K SRAM, 8x of the Uno, 2x of the Mega.
I have boards available in Uno and other form factors.
Hi CSTEnergyGuy,
without seeing your code is hard to give your best advise. Please always post your code if you ask something about it.
Anyway, if you expect unknown amount of data and you have to store it in a memory, you have to declare a maximum size. This is because you have limited resources. In the first place it doesn't matter if this are 64kb, 640kb or 6400kb.
Two different solutions to your problem.
- Declare global buffer (512kb should be no problem, if more you have to check your needs)
- Allocate your array dynamically but then you have to deal with the fragmented heap.
I always prefer solution one, because it's easier to handle it.
Nighti:
- Declare global buffer (512kb should be no problem, if more you have to check your needs)
On a 2k Arduino ?
...R
You are right. 512 byte Forget all the 'k' in my previous post
"malloc" and "Arduino" (especially UNO) would make an oxymoron.