0

I have a struc called player, and I need to make an array of MAX players, so I based on the following page C - initialize array of structs, like so:

DEFINE MAX 200

typedef struct
{
   int ID;
} Player;

Player* PlayerList = malloc(MAX * sizeof(Player));

Problem is I keep getting the following error

error: expected expression before ‘=’ token
error: initializer element is not constant

Base code:

#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;
}
4

2 回答 2

2

您不能malloc()从任何函数外部调用。只需声明Player* PlayerList;,并让你做的第一件事main()成为PlayerList = malloc(MAX * sizeof(Player));

于 2013-05-02T00:12:01.760 回答
1

在旧类型“C”中,您不能只使用常量进行初始化。

改写

Player* PlayerList = malloc(MAX * sizeof(Player));

Player* PlayerList;
PlayerList = malloc(MAX * sizeof(Player));

添加 EG:

#include <stdlib.h>

#define MAX 200

typedef struct
{
   int ID;
} Player;

Player* PlayerList=NULL;

int main(void){
    PlayerList = malloc(MAX * sizeof(Player));
    return 0;
}
于 2013-05-02T00:11:26.547 回答