Sam
Sam

Reputation: 13

Unable to create global array of structs

I am trying to make a global array of structs, however the way in which I thought I would go about this doesn't work. For the application I need requires it be be global however will not know the size until inside the main() function. My code is as follows:

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//
struct player {
    char letter;
};

struct player *players;

int main(int argc, char** argv){
    check _variables();
    int *inpBuff;
    inpBuff = convert_input(argv[1], argv[2]);
    int numPlayers = inpBuff[0];
    players =  malloc(numPlayers*sizeof(player));
    return 1;
}

I receive the error: error: 'player' undeclared (first use in this function) players = malloc(numPlayers*sizeof(player));

Upvotes: 1

Views: 84

Answers (1)

Gaurav
Gaurav

Reputation: 1600

SOURCE OF ERROR--> You are using player instead of players in malloc which is incorrect. Player is the name of struct and you need the pointers name in malloc.

First --> You need to correct your malloc statement --> use players = malloc(numPlayers*(sizeof(*players));

Second --> When return type of main() function is int then your return statement seems to be missing.

Upvotes: 2

Related Questions