Member Avatar for karoma

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

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?

Just use

struct mys
{};

struct mys * pointer = (struct mys*)malloc(num_elements * sizeof(struct mys));

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:

free(mem);
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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.