D
D
Dmitriy2019-12-04 12:20:19
C++ / C#
Dmitriy, 2019-12-04 12:20:19

How to fix "Expression must have a constant value"?

I declare an array:

int rows = 7;
  int cols = 8;
  float array[rows][cols];

Error "Expression has a constant value".
How to fix?
I somehow fixed it with sizeof/malloc, I just forgot

Answer the question

In order to leave comments, you need to log in

5 answer(s)
C
CityCat4, 2019-12-04
@CityCat4

Don't engage in such nonsense.
Either either

float *aptr;
aptr = (float *) calloc(sizeof(float), 7 * 8);

R
res2001, 2019-12-04
@res2001

The way you use an array is called VLA ( Variable Length Array ). Appeared only in the C99 standard. It doesn't exist in C++.
To use VLA, the compiler must explicitly set the standard to be used. For gcc: -std=c99 or -std=c11. C11 is the 2011 standard.
If you use a compiler from Microsoft (as part of MSVS for example), then I can sadden you - Microsoft has never tried to support the C standards. VLA support is not there and is unlikely to be in the near future.
But it is generally not recommended to use VLA without a clear understanding of what it is, how it works and what consequences it can lead to. For example, at one time in the Linux kernel there was a whole company for uprooting code from the VLA. So it's better to use dynamic arrays or static arrays with constant dimensions.

G
GavriKos, 2019-12-04
@GavriKos

Read about dynamic arrays in C.
And the fix is ​​simple - make rows and cols constants, as the compiler writes about.

W
wisgest, 2019-12-04
@wisgest

#define rows 7
#define cols 8
float array[rows][cols];

R
Roman, 2019-12-05
@myjcom

float** array = malloc(M * sizeof(*float));
for(int i = 0; i < M; i++)
  array[i] = malloc(N * sizeof(float));

In C, you don't need to cast after malloc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question