Kobek
Kobek

Reputation: 1211

C Program in visual studio. Array with a constant value is treated as an error

I've tried looking for a solution to this problem, but with no luck. I have a program written in C, and in it I have an array that is defined like this:

int sevensArray[SEVENS_COUNT];

When compiling it I get an error that says "Expression must be of constant value".

I realize you cannot have the array size to be a variable, as the compiler should know how much memory it needs to allocate.
The thing is... SEVENS_COUNT is defined as a const INT in the program like so:

const int SEVENS_COUNT = counter;

My question is why is this still seen as an error. Is it because even though SEVENS_COUNT is a const it is assigned to counter, which is actually a variable and how can I fix that.

I tried the same code and it compiles perfectly fine on other compilers such as Code::Blocks.

Upvotes: 2

Views: 1028

Answers (1)

Dimitar
Dimitar

Reputation: 4783

const doesn't mean constant, but read-only.

1) Best way: make it dynamic instead of static. Use malloc or if you want it additionally initialized calloc. At the end don't forget to free the allocated memory.

You would need a pointer however instead of an array, but for your purpose they are essentially the same. Like:

int *sevensPtr = malloc(sizeof(int) * counter);
//your code
free(sevensPtr);

If you don't know how to access an element from the allocated memory, it is analogous to array:

sevensArray[0] == sevensPtr[0] == *(sevensPtr + 0)

2) Another way is to use VLAs. Then you could assign a variable-length to your array. Such as:

 void foo(int n)  //and pass counter
 {
   int x[n];
   process(x, n); 
 }

In words, pass it as an argument of a/the function and then declare the array locally.

Also you could simply use alloca.

As about the IDE, the one supports variable-size declaration, whereas the other doesn't. But that depends on the C standard being used and not on the environment itself.

Upvotes: 2

Related Questions