N
N
Nulltiton2022-03-15 18:00:46
C++ / C#
Nulltiton, 2022-03-15 18:00:46

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

3 answer(s)
R
res2001, 2022-03-15
@res2001

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.

V
Vasily Bannikov, 2022-03-15
@vabka

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];
}

R
rPman, 2022-03-15
@rPman

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 question

Ask a Question

731 491 924 answers to any question