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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
GrimThor3
  • 171
  • 1
  • 10
  • 1
    `#define numPlayers 2`, declaring an `int` as `const` is not a constant for purposes of array declaration. – David C. Rankin Apr 11 '18 at 02:37
  • 2
    Also, you have the arguments to [`calloc(size_t num, size_t size)`](http://en.cppreference.com/w/c/memory/calloc) backwards. – 001 Apr 11 '18 at 02:41
  • 2
    seems ancient version of C. Works weell in modern compilers. BTW #define style `is medicine worse than the disease` – Jacek Cz Apr 11 '18 at 02:44
  • [don't cast the result of the `malloc` family in C](https://stackoverflow.com/q/605845/995714) – phuclv Apr 11 '18 at 14:58

2 Answers2

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];
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
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.

Ash
  • 473
  • 2
  • 10