I have a Team struct which has field of pointer to a struct called Player. I have a function that returns a pointer to a player, everytime the user adds a player, it suppose to re-allocate the memory size of the "array" that contains the players, and to add a new player. like a dynamic array of players. for some reason it only accepts one player. I have seen problems that resembles mine, but no answer worked. Please help me.
the code:
struct Player {
float pointsAverage;
int uniformNumber;
int pointsOfLastFiveGames[5];
char *playerName;
};
struct Team {
int numberOfPlayers;
char *managerName = nullptr;
struct Player *players = (Player*)malloc(sizeof(Player));
};
struct Player* setPlayer(){
struct Player *player = NULL;
player = (struct Player*)malloc(sizeof(struct Player));
char name[81] = {0};
int jerseyNumber = -1;
int sumOfPoints = 0;
int currentPoint = 0;
printf("Player name?\n");
scanf("%s", &name);
int nameLength = strlen(name);
player->playerName = (char*)malloc(sizeof(char)*(nameLength + 1));
strcpy(player->playerName, name);
printf("Jesrsey number?\n");
scanf("%d",&jerseyNumber);
player->uniformNumber = jerseyNumber;
printf("Player point history?\n");
int i;
for (i=0; i<NUM_OF_PLAYER_POINT; i++) {
scanf("%d",¤tPoint);
sumOfPoints+=currentPoint;
}
player->pointsAverage = (float)(sumOfPoints/NUM_OF_PLAYER_POINT);
return player;
}
struct Team* setTeam(){
//initialize a team
struct Team *team = NULL;
team = (struct Team*) malloc(sizeof(struct Team));
team->managerName = NULL;
team->numberOfPlayers = 0;
team->players = NULL;
int usersChoice = -1;
// temp char array of name so i can take its size after user input
char name[81] = {0};
printf("Hello, please enter manager's name:\n");
scanf("%s",&name);
// checking the length of the user input.
int nameLength = strlen(name);
// dynamically allocating the manangerName memory space.
team->managerName = (char *)malloc(sizeof(char) * (nameLength + 1));
// setting the managername to the name the user typed.
strcpy(team->managerName, name);
int playerCounter = 1;
int addedPlayerCounter = 0;
while (1){
printf("Would you like to buy a player (1) yes (else) no?\n");
scanf("%d",&usersChoice);
if(usersChoice==1){
usersChoice = 0;
playerCounter++;
Player *temp = NULL; // here I tried make a new pointer but it still doesn't work
struct Player* tempPlayer = setPlayer();
temp = (Player*)realloc(team->players, sizeof(Player)*playerCounter);
(temp+(sizeof(Player)*addedPlayerCounter))->playerName = tempPlayer->playerName;
(temp+(sizeof(Player)*addedPlayerCounter))->pointsAverage = tempPlayer->pointsAverage;
addedPlayerCounter++;
team->numberOfPlayers++;
}else{
return team;
}
}
}
the main function just calls the setTeam function.