Go Down

Topic: quick question about declaring an array (Read 846 times) previous topic - next topic

stoopkid

If I declare an array inside of my void loop(), can I change the number of items each time the loop starts over? I've only ever programmed in visual basic, and the array's there were much easier, i didn't have to worry about declaring its size.

And speaking of that, can I change the size of an array if its already declared?

Thanks

stoopkid

Ugh, alright so upon trying it out, I seem to have found that the size of an array must be constant. Is there any way around this other than to remember how many values I want to use and ignoring the rest?

Groove

Quote
, I seem to have found that the size of an array must be constant

A static or global one, maybe, but not an automatic one.
Code: [Select]
void test (int a)
{
  int array [a];
}
Per Arduino ad Astra

stoopkid

Oh okay, I just stupidly declared the array twice, trying to move it. So this is okay? :

Code: [Select]

void loop() {
Fade = map(AnalogInputValue,0,1023,0,Size);
int Array[Fade];
}


Is it okay if this value is different every time it runs the loop?

Groove

#4
Feb 26, 2011, 11:47 am Last Edit: Feb 26, 2011, 12:04 pm by Groove Reason: 1
As long as Size is not too big for the stack (because that's where the array will be put), yes.

Of course, you should put it on the heap (use malloc) but don't forget to free it when you've finished with it.
Per Arduino ad Astra

stoopkid

#5
Feb 26, 2011, 12:07 pm Last Edit: Feb 26, 2011, 12:09 pm by stoopkid Reason: 1
So I can't just declare it at the beginning of the loop? I have to use Malloc? Is the array freed at the end of the function automatically?

What I mean is, at the end of the function, Im done with the array. I entirely refill the array when the function starts again. So what do I need to do to free it at the end of the function?

Groove

No, you don't have to use malloc, but it is better if you do.
Quote
So what do I need to do to free it at the end of the function?

Call "free".
Per Arduino ad Astra

stoopkid


Go Up