2

I have this expression:

const int numPlayers = 2;
player players[numPlayers];

This is an array of user-defined type players (using struct). However, I get an error saying that numPlayers has to be a constant value.

expression must have a constant value

What am I doing wrong?


I have also initialized the array like this:

player *players = (player*)calloc(sizeof(player), numPlayers);

But I cannot access any of the local variables of the struct without the program crashing.

4
  • 1
    #define numPlayers 2, declaring an int as const is not a constant for purposes of array declaration. Commented Apr 11, 2018 at 2:37
  • 2
    Also, you have the arguments to calloc(size_t num, size_t size) backwards. Commented Apr 11, 2018 at 2:41
  • 2
    seems ancient version of C. Works weell in modern compilers. BTW #define style is medicine worse than the disease Commented Apr 11, 2018 at 2:44
  • don't cast the result of the malloc family in C Commented Apr 11, 2018 at 14:58

2 Answers 2

2

In C99, the below works fine inside a function. It is a variable length array (VLA).

const int numPlayers = 2;
player players[numPlayers];

Otherwise use a #define for a true constant.

#define numPlayers 2
player players[numPlayers];
Sign up to request clarification or add additional context in comments.

Comments

0

const are not true constants, the compiler will not allow you to change the value only. I will suggest use #define numPlayers 2 instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.