我有一个名为player的结构,我需要制作一系列MAX玩家,所以我基于以下页面C - initialize array of structs,如下所示:
DEFINE MAX 200
typedef struct
{
int ID;
} Player;
Player* PlayerList = malloc(MAX * sizeof(Player));
问题是我一直收到以下错误
error: expected expression before ‘=’ token
error: initializer element is not constant
基本代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX = 200;
typedef struct
{
int ID;
} Player;
Player *PlayerList;
int start()
{
PlayerList = malloc(MAX * sizeof(Player));
return 1;
}
int main(int argc, char const *argv[])
{
/* code */
return 0;
}
答案 0 :(得分:2)
您无法从任何功能之外调用malloc()
。只需声明Player* PlayerList;
,让您在main()
中执行的首批操作之一为PlayerList = malloc(MAX * sizeof(Player));
。
答案 1 :(得分:1)
在旧类型“C”中,不能仅使用常量进行初始化。
重写
Player* PlayerList = malloc(MAX * sizeof(Player));
到
Player* PlayerList;
PlayerList = malloc(MAX * sizeof(Player));
添加E.G。:
#include <stdlib.h>
#define MAX 200
typedef struct
{
int ID;
} Player;
Player* PlayerList=NULL;
int main(void){
PlayerList = malloc(MAX * sizeof(Player));
return 0;
}