简体   繁体   English

C中的常量整数和数组初始化

[英]Constant Integer and Array Initialization in C

I have this expression: 我有这样的表达:

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

This is an array of user-defined type players (using struct). 这是一组用户定义的类型播放器(使用struct)。 However, I get an error saying that numPlayers has to be a constant value. 但是,我得到一个错误,说numPlayers必须是一个常量值。

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. 但是在程序崩溃的情况下,我无法访问结构的任何局部变量。

In C99, the below works fine inside a function. 在C99中,下面的函数内部工作正常。 It is a variable length array (VLA). 它是一个可变长度数组 (VLA)。

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

Otherwise use a #define for a true constant . 否则使用#define作为真常量

#define numPlayers 2
player players[numPlayers];

const are not true constants, the compiler will not allow you to change the value only. const不是真正的常量,编译器不允许您仅更改值。 I will suggest use #define numPlayers 2 instead. 我建议改用#define numPlayers 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM