/* ============================================================================ Name : Dog.c Author : David Mutchler, November 2008. Description : A simple Dog structure and associated functions. ============================================================================ */ #include "Dog.h" // Constructs and returns a pointer to a Dog with the given characteristics. Dog* constructDog(int age, float weight, char* name, char* breed, char* owner) { Dog* dog = (Dog*) malloc(1 * sizeof(Dog)); dog->age = age; dog->weight = weight; strcpy(dog->name, name); dog->breed = (char*) malloc((strlen(breed) + 1) * sizeof(char)); strcpy(dog->breed, breed); dog->owner = (char*) malloc((strlen(owner) + 1) * sizeof(char)); strcpy(dog->owner, owner); return dog; } // Prints the given Dog's characteristics. void printDog(Dog* dog) { printf("%d %f %s %s %s\n", dog->age, dog->weight, dog->name, dog->breed, dog->owner); } // Deallocates the space allocated for the given Dog and its fields. void destructDog(Dog* dog) { free(dog->breed); free(dog->owner); free(dog); } // Constructs and returns a pointer to a random Dog. Dog* constructRandomDog() { int age; float weight; char* name; char* breed; char* owner; age = rand() % 15; weight = (float) (rand() % 100); name = randomString(1 + rand() % 6); breed = randomString(1 + rand() % 5); owner = randomString(1 + rand() % 10); return constructDog(age, weight, name, breed, owner); } // Returns a random string of lowercase letters (a-z) of the given length. char* randomString(int size) { char* string; int k; string = (char*) malloc((size + 1) * sizeof(char)); for (k = 0; k < size; ++k) { string[k] = 'a' + (char) (rand() % 26); } string[size] = '\0'; // Null-terminated string return string; }