Can use variable to assign array size?

Hi,
Can I used:

int a=8;
int Array[a];

or not?
Thanks
Adam

Hello

Yes, of course, try it

Thanks.
int Array[‘a’];

That’s not your original question…

‘a’ is not a.

Try doing what you asked. Tell us it worked. Show the code where it did, and we all learn something.

a7

Yup, that will make you an array of 97 int(s).

Thanks for detail.
the [a] got compiling error:
'a' compiling passed.
I have a picture upload failed.

int a = 8;
int arraya[a];

void setup() {
  // put your setup code here, to run once:

Serial.begin(9600);
  Serial.println("xxx_setup!");
  Serial.print("File   : "), Serial.println(__FILE__);
  Serial.print("Date   : "), Serial.println(__DATE__);
  
}

void loop() {
  // put your main code here, to run repeatedly:
  for (int i = 0; i < a; i++)
  {
    arraya[i] = i;
    Serial.print(arraya[i]);
  }
  delay(1000);
}

ERROR:

Arduino: 1.8.16 (Windows 7), Board: "Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

arraya_test:3:13: error: array bound is not an integer constant before ']' token

 int arraya[a];

             ^

C:\Users\HUA.DELLV-PC\Documents\Arduino\arraya_test\arraya_test.ino: In function 'void loop()':

arraya_test:19:5: error: 'arraya' was not declared in this scope

     arraya[i] = i;

     ^~~~~~

exit status 1

array bound is not an integer constant before ']' token



This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Yeah, because you can’t do that at file scope.

But why do you need or want to do that?

a7

Chances are you'll never want an array of NEGATIVE size. So, 'int' is not the best choice. Any unsigned type would be better. But, there's actually a specific type for this purpose 'size_t'.

Also, the compiler error is quite clear. It wants the array size specified with a constant. So:

const size_t a = 8;
int Array[a];

Thanks.
do you mean why do I use ['a']?
because I have few of array[] with the same size, and I need modify the size when to do the test.

Sure you can:

const size_t a = 8;
int Array[a];
const size_t arraySize = sizeof(Array)/sizeof(Array[0]);

void setup() {
  Serial.begin(115200);
  delay(1000);
  Serial.println(arraySize);
}

void loop() {
}

Great!
Thank you gfvalvo.

You added, and even pointed out the necessity of doing, the const.

a7