Answer the question
In order to leave comments, you need to log in
How to set the size of an array using a constant?
I'm trying to create an array by setting the dimension to a constant, but I get errors: "expression must have a constant value", "constant expression required", "unable to allocate memory for an array of constant zero size".
The code:
const int size = 10; // размерность массива
int a[size];
Answer the question
In order to leave comments, you need to log in
Set with define.
The dimension of a static array must be known at compile time. And the value of a constant in the general case may not be known during compilation. Unfortunately, constexpr was not brought to C from the pluses.
1. Show the full code
2. Not dimension, but size
3. What kind of compiler?
Here it is normally assembled on gcc:
void main() {
const int size = 10;
int array[size];
}
you can create your array of the required size already during execution and not at the compilation stage, then the size can be in the variable
int * a this is the definition of an array without initialization, the size of the array compiler is unknown, and the initialization itself should be carried out by the new operator, which means that somewhere at the end you need free memory with delete
upd. it was for c++,
but for c it turns out you need to use malloc and free, respectively
int *a=new int[size];
int *a=(int*)malloc(size*sizeof(int));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question