// simple code to show stucts and pointers
// Marc Chee (marc.chee@unsw.edu.au)
#include <stdio.h>
#include <string.h>
#define MAX_NAME_LENGTH 50
#define MAX_POWER_LENGTH 50
#define MAX_NUM_POWERS 5
struct person {
char name[MAX_NAME_LENGTH];
struct person *secret_identity;
char powers[MAX_NUM_POWERS][MAX_POWER_LENGTH];
int num_powers;
struct person *arch_nemesis;
};
void give_power(char power[MAX_POWER_LENGTH], struct person *hero);
void display_person(struct person *hero);
void setup_person(struct person *hero, char name[MAX_NAME_LENGTH]);
int main(void) {
struct person bruce;
setup_person(&bruce, "Bruce Wayne");
display_person(&bruce);
give_power("Super rich", &bruce);
display_person(&bruce);
// Tragedy strikes, Bruce's parents are murdered
// Bruce decides to become a vigilante
// based on his own fear of bats
struct person batman;
setup_person(&batman, "Batman");
give_power("Fearless", &batman);
give_power("Ninjitsu", &batman);
give_power("Tech gadgets", &batman);
give_power("Brooding", &batman);
give_power("Gravelly Christian Bale Voice", &batman);
give_power("Supersonic flight", &batman);
bruce.secret_identity = &batman;
display_person(&bruce);
// No hero is a true hero without something
// to fight against
struct person joker;
setup_person(&joker, "The Joker");
give_power("Comedy", &joker);
give_power("Psychopathic", &joker);
give_power("Henchmen", &joker);
batman.arch_nemesis = &joker;
display_person(&bruce);
}
// give_power will add a power to a person
// It will add the string to the array of strings
// called powers, if the person still has
// space to add 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++;
}
}
// Displays a person's information
// including calling display_person() again
// for their secret identity
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++;
}
if (hero->secret_identity != NULL) {
printf("Secret Identity:\n");
display_person(hero->secret_identity);
} else {
printf("-----------\n");
}
if (hero->arch_nemesis != NULL) {
printf("Arch Nemesis:\n");
display_person(hero->arch_nemesis);
}
}
void setup_person(struct person *hero, char name[MAX_NAME_LENGTH]) {
strcpy(hero->name, name);
hero->secret_identity = NULL;
hero->num_powers = 0;
hero->arch_nemesis = NULL;
}
Resource created Tuesday 16 July 2019, 11:18:06 PM, last modified Monday 29 July 2019, 05:52:17 PM.
file: bat_demo.c