define an array dynamicly

Hey,

Im trying to define an array and getting some errors.

int x = 10;
int y [x];

So, basicly i want the array size to equal 10. But I get an error
"array bound is not an integer constant"
I really want to define the array size dynamicly.

Cheers,

Nick D

Hi Nick,
This is a tricky area. If you just want to easily change the size of the array at compile time you could do this:
#define ARRAY_SIZE 10 // you can change 10 to another value at compile time
int y[ARRAY_SIZE];

But if you want to change the size while the sketch is running you need to use something like the C dynamic memory allocation function called malloc() ;

You can find information on using malloc in one of the many references on the C languge but its not easy to use and it is easy to run out of RAM if you are not careful, so its better to allocate the maximum you will need statically if you can. Can you say more about your application and why you want dynamic allocation?

I think ive got a work around, but yeah it would probably just be easy to set the array to a max size and just not exceed that.

hi there,

i think you might be interested in a set of functions which i added to the playground under the section "RAM and Eeprom". By using the functions you are able to dynamically allocate arrays. It's designed to be small, fast and use as minimal memory as possible.

greetz, Sander