Morki
Morki

Reputation: 215

Initialize array of structs - c code error

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

Upvotes: 0

Views: 384

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40145

You can not use only constant for initialization in old type 'C'.

rewrite

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

to

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

Add 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;
}

Upvotes: 1

You can't call malloc() from outside of any function. Just declare Player* PlayerList;, and let one of the first things you do in main() be PlayerList = malloc(MAX * sizeof(Player));.

Upvotes: 2

Related Questions