// A Battle Royale player tracker
// This is a linked list demo
// Marc Chee (marc.chee@unsw.edu.au), July 2019
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 1000
struct player {
char name[MAX_NAME_LENGTH];
struct player *next;
};
struct player *createPlayer(
char inputName[MAX_NAME_LENGTH], struct player *inputNext
);
void printPlayers(struct player *p);
int main(void) {
struct player *head = NULL;
head = createPlayer("Marc", NULL);
head = createPlayer("AndrewB", head);
head = createPlayer("Batman", head);
head = createPlayer("Leonardo", head);
printPlayers(head);
return 0;
}
// Mallocs and creates a node using the inputName and inputNext pointer
// returns a pointer to the newly created node
struct player *createPlayer(
char inputName[MAX_NAME_LENGTH], struct player *inputNext
) {
struct player *n = malloc(sizeof(struct player));
if (n == NULL) {
printf("Malloc failed, unable to create player. Program will exit.\n");
exit(1);
}
strcpy(n->name, inputName);
n->next = inputNext;
return n;
}
void printPlayers(struct player *p) {
while(p != NULL) {
fputs(p->name, stdout);
putchar('\n');
p = p->next;
}
}
Resource created Monday 22 July 2019, 11:41:44 PM.
file: battleLec.c