Define Array w/ Variable

Hi, I want to define an array that is the size of an int variable. Is this possible? The IDE doesn't let me define an array size using a variable directly. Is there any other way? Thanks, I'm new to this, I appreciate any help.

Yes.

You can use alloca to allocate stack space for the array. This is appropriate if the array only has to persist for the lifetime of a function call.

You can use malloc / new to allocate heap space for the array. This is appropriate if the array persists for the lifetime of your application.

I'm not sure what your problem is.

byte array1[2];  // array with 2 bytes; two bytes is the size of an int on a lot of arduinos.

void setup()
{
  byte array2[sizeof(int)]; // array with the same size as an int; any arduino

  int x = 2;
  byte array3[x]; // array with a size of two bytes.
}

You can declare a local array variable using an int as the array size but not a global or static one.

  int aSize = 10;
  byte anotherArray[aSize];    //compiles OK
  static byte anArray[aSize];  //will not compile
storage size of 'anArray' isn't constant

See VLA’s in C99

Mark

You can declare a local array variable using an int as the array size but not a global or static one.

If the variable is const, you can use it to size a global array. But, then, it's not exactly a variable...

Thank you everyone!