I'm programing a game that takes two players. When the game is over I want to start playing with two new players but keep the score of the previous game.
I have a composite data type struct to create player
which is working.
How do I create one more set of two players and access their data, without erasing the previous ones?
#include <stdio.h>
#include <stdlib.h>
struct player
{
char *name;
int games;
};
//function prototypes
void getPlayerInfo(struct player *playerPtr);
void printPlayerInfo(struct player playerOn[]);
void getPlayerInfo(struct player *playerPtr)
{
// Allocate memory on the stack
playerPtr->name = malloc(10 * sizeof(char));
printf("Enter Player name:");
fgets(playerPtr->name, 10, stdin);
}
void printPlayerInfo(struct player playerOn[])
{
for (int i = 0; i < 2; i++)
{
printf("Player #%d Name: %s\n", i + 1, playerOn[i].name);
printf("==========================================\n");
}
}
int main()
{
struct player *playerOn = malloc(2 * sizeof(struct player));
for (int i = 0; i < 2; i++)
{
getPlayerInfo(&playerOn[i]);
}
printPlayerInfo(playerOn);
for (int i = 0; i < 2; i++)
{
free(playerOn[i].name);
}
free(playerOn);
return 0;
}