初始化结构数组 - c代码错误

时间:2013-05-02 00:05:28

标签: c pointers struct

我有一个名为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;
}

2 个答案:

答案 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;
}