C++ Expression must have constant value
You can't enter a non-constant value between the brackets when you declare your array:
int Amta[size];
Since you're getting size
from the user, the compiler can't tell ahead of time how much memory it needs for Amta
. The easiest thing to do here (especially for an exercise) is to just choose a relatively large value and make that the constant allocation, like:
int Amta[1024];
And then if you want to be careful (and you should) you can check if (size > 1024)
and print an error if the user wants a size that's beyond the pre-allocated bounds.
If you want to get fancy, you can define Amta
with no pre-set size, like int *Amta;
and then you allocate it later with malloc
:
Amta = (int *)malloc(sizeof(int) * size);
Then you must also free Amta
later, when you're done with it:
free(Amta);
C++ doesn't allow variable length arrays. The size must be a constant. C99 does support it so if you need you can use a C99 compliant compiler. Some compilers like GCC and Clang also support VLA as an extension in C++ mode
But if C++ is a must then you can use alloca
(or _alloca
on Windows) to allocate memory on stack and mimic the C99 variable length array behavior
Amta = (int *)alloca(sizeof(int) * size);
This way you don't need to free the memory after going out of scope because the stackframe will automatically be restored. However you need to be very careful while using this. It's still better to use std::vector
in C++ for these purposes