I'm trying to create an array of structs, of which the array size is defined by the user in the program. eg. p[0], p[1], p[2].....

typedef struct
int score;

void main()
int numPlayers;

printf ("\nEnter number of players (1 - 4)\n");
scanf ("%d", &numPlayers);


The problem is I don't know where to go from here. I've tried this, but it says I need to enter a constant value.

player p[numPlayers];

I believe I can use malloc, but I'm quite unsure about how to use it.
Any tips?

6 Years
Discussion Span
Last Post by death_oclock

There are a few other considerations when using malloc . The function returns NULL if memory can't be allocated, so you need to test for that possibility:

void *mem = malloc(size);
if(mem == NULL) // or if(!mem)
    // error handling

You also need to free the memory when you're done:

mem = NULL;

These are generic examples that you'll have to modify for your program.

This wikipedia article has much more information if you're interested.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.