example-3.3.c
example-3.3.c · 2.0 KB
From the archive c_pointers_examples.tar.gz
Download the archive « Back to the archive contents
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct player {
struct player *next;
char name[20];
int current_hp;
int max_hp;
};
struct player *first_player = NULL;
struct player *create_player( char *name, int chp, int mhp )
{
struct player *plyr;
plyr = (struct player *) malloc( sizeof(struct player) );
if ( plyr == NULL )
{
printf( "Memory Error!\n\r" );
exit(1);
}
strncpy( plyr->name, name, 19 );
plyr->name[19] = '\0';
plyr->next = NULL;
plyr->current_hp = chp;
plyr->max_hp = mhp;
return plyr;
}
void add_player( struct player *plyr )
{
struct player *insert;
if ( first_player == NULL )
first_player = plyr;
else
{
insert = first_player;
while ( insert->next )
insert = insert->next;
insert->next = plyr;
}
}
struct player *find_player( char *name )
{
struct player *plyr;
for ( plyr = first_player; plyr != NULL; plyr = plyr->next )
if ( !strcmp( plyr->name, name ) )
return plyr;
return NULL;
}
void free_player( struct player *plyr )
{
struct player *find;
struct player *delete;
if ( first_player == plyr )
{
delete = first_player;
first_player = delete->next;
free(delete);
return;
}
for ( find = first_player; find && find->next; find = find->next )
{
if ( find->next == plyr )
{
delete = find->next;
find->next = delete->next;
free(delete);
return;
}
}
}
int main()
{
int i;
char buf[20];
struct player *plyr;
struct player *plyrs[5];
for ( i = 0; i < 5; i++ )
{
sprintf( buf, "MudByter%d", i );
plyrs[i] = create_player( buf, i*2, i*5 );
add_player( plyrs[i] );
}
for ( i = 0; i < 5; i++ )
{
sprintf( buf, "MudByter%d", 4-i );
plyr = find_player( buf );
if ( !plyr )
continue;
printf( "%s has %d/%d hp.\n\r", plyr->name,
plyr->current_hp, plyr->max_hp );
}
for ( i = 0; i < 5; i++ )
free_player( plyrs[i] );
return 0;
}