// First look at multi-file projects
// This code is an adaptation of a live stream on pointers and structs

// Marc Chee (cs1511@cse.unsw.edu.au), October 2020

// Implementation of the person that is declared in person.h

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "person.h"


struct person {
    char name[MAX_NAME_LENGTH];
    char powers[MAX_NUM_POWERS][MAX_POWER_LENGTH];
    int num_powers;
};

// allocate memory for a struct person,
// initialise information
// and return the pointer to the memory
Person create_person(char name[MAX_NAME_LENGTH]) {
    Person hero = malloc(sizeof (struct person));
    strcpy(hero->name, name);
    hero->num_powers = 0;
    return hero;
}

void free_person(Person hero) {
    free(hero);
}

// Add a power.
// Do nothing if the person already has MAX_NUM_POWERS powers
void give_power(char power[MAX_POWER_LENGTH], struct person *hero) {
    if (hero->num_powers < MAX_NUM_POWERS) {
        strcpy(hero->powers[hero->num_powers], power);
        hero->num_powers++;
    }
}

// print out information about the person
void display_person(struct person *hero) {
    printf("Name: %s\n", hero->name);
    printf("Powers:\n");
    int i = 0;
    while(i < hero->num_powers) {
        fputs(hero->powers[i], stdout);
        putchar('\n');
        i++;
    }
    printf("----------\n");
}

Resource created Wednesday 27 January 2021, 01:16:14 PM, last modified Wednesday 31 March 2021, 08:03:03 PM.

file: person.c


Back to top

COMP1511 21T1 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G