I am trying to create a game, and at some point when the user come inside the game, there will be created a structure for that player. If the player type its name the game prompts the player with the following:
Type player name:> George
Choose one of the following Otions:
[+]1) to remove George from player List.
[+]0) to keep George.
The player need to type 3 names and decide if one or all of them should be removed or keep.
The problem I have is that I cannot keep the created (remained) list if the player decide to delete one or more from list.
Here is a part of the program which can be compiled:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define PERCENT 5
#define LEFT "left"
#define RIGHT "Right"
struct node {
int player_ID;
struct node* prev;
struct node* next;
char move_player[256];
char player_name[ 31 ];
} node;
struct node *root;
struct node *current;
struct node *player_node( int player_ID, const char *player_name );
void delete_player ( void *player_list );
int main( void )
{
char name[256] = { 0 };
int i = 0, clean;
root = player_node( PERCENT, RIGHT );
current = root;
do{
struct node *player = player_node( PERCENT, LEFT );
player->prev = current;
current->next = player;
current = player;
printf( "Type player name:> ");
if ( fgets( name, 256, stdin ) == NULL )
{
printf("Error, fgets()\n");
exit( EXIT_FAILURE );
}
name[ strcspn( name, "\n" ) ] = '\0';
strncpy( player->player_name, name, strlen( name ) );
printf( "Choose one of the following Otions:\n" );
printf( "\t[+]1) to remove %s from player List.\n", current->player_name );
printf( "\t[+]0) to keep %s.\n", current->player_name );
int opt = 0;
if ( scanf( "%d", &opt) != 1 )
{
printf("Error, scanf()\n");
}else if ( opt == 1 )
{
delete_player ( player );
}
while ( ( clean = getchar() ) != '\n' && clean != EOF );
i++;
}while( i < 3 );
struct node *tmp = root->next;
while ( tmp != NULL )
{
printf( "Name = %s", tmp->player_name );
tmp = tmp->next;
}
free( root );
}
struct node *player_node( int player_ID, const char *const movement )
{
struct node *player = malloc( sizeof( struct node ) );
player->prev = NULL;
player->next = NULL;
player->player_ID = player_ID;
strncpy( player->move_player, movement, strlen( movement) );
strncpy( player->player_name, "NULL", 5 );
return player;
}
void delete_player ( void *player_list )
{
struct node *local_client = (struct node* )player_list;
if ( local_client == current )
{
current = local_client->prev;
current->next = NULL;
} else
{
local_client->prev->next = local_client->next;
local_client->next->prev = local_client->prev;
}
free( local_client );
}
If the code reaches this:
struct node *tmp = root->next;
while ( tmp != NULL )
{
printf( "Name = %s", tmp->player_name );
}
There are no remain players in the list, because the List is not printed.
Why is the list empty?