0

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;
}
Laurel
  • 5,965
  • 14
  • 31
  • 57
Bruno
  • 27
  • 5
  • Side note: you allocate 10 bytes for `name` but then tell `fgets` to read up to 30 bytes. – 001 Dec 31 '21 at 14:39
  • Also, `fgets` reads up to a newline char and will include that newline char in the string. [Removing trailing newline character from fgets() input](https://stackoverflow.com/a/28462221) – 001 Dec 31 '21 at 14:40
  • Please see if you can clarify your question, I have a hard time understanding what you really want. – Bo R Dec 31 '21 at 14:42
  • It looks like you want a 2d array. Something like `struct player[n][2]` where `n` is the number of pairs. See: [Malloc a 2D array in C](https://stackoverflow.com/a/36890904) – 001 Dec 31 '21 at 14:44
  • Bo R, maybe I wasnt clear enough. Iḿ 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 previews game. – Bruno Dec 31 '21 at 15:26
  • Thanks Johnny Mopp I missed those mistakes. – Bruno Dec 31 '21 at 15:27
  • Bo R, keep the score and names of previews players – Bruno Dec 31 '21 at 15:42

0 Answers0