Demonstration of some struct features and use.
Fork of ArraySizeof by
main.cpp
- Committer:
- CSTritt
- Date:
- 2017-11-08
- Revision:
- 4:b36f0369c752
- Parent:
- 3:45a53383e09f
File content as of revision 4:b36f0369c752:
/* Project: StructPlay File: main.cpp Ported to mbed/Nucleo by: Dr. C. S. Tritt Last revised: 11/7/17 (v. 1.1) Demonstrates various struct usage. All of this code was taken from Horton Chapter 11 and modified. */ #include "mbed.h" struct Family { char name[20]; int age; char father[20]; char mother[20]; }; typedef struct Family Family; // Declare the function. bool siblings(Family member1, Family member2); bool siblingsWP(Family const *pMember1, Family const *pMember2); int main(void) { // Create a Horse structure. struct Horse { int age; int height; char name[20]; char father[20]; char mother[20]; }; typedef struct Horse Horse; Horse trigger = { .name = "Trigger", .mother = "Wesson", .father = "Smith" }; trigger.age = 30; trigger.height = 15; printf("Trigger's old mom: %s.\n", trigger.mother); strcpy(trigger.mother, "Crisco"); // Size should be checked! printf("Trigger's new mom: %s.\n", trigger.mother); Horse myHorse; // Structure variable declaration. // Initialize the structure variable from entered data. printf("Turn local echo on!\n" ); printf("Enter the name of the horse: " ); scanf("%s", myHorse.name); // Read the name. Dangerous. printf("Name set to: %s.\n", myHorse.name); printf("How old is %s? ", myHorse.name ); scanf("%d", &myHorse.age ); // Read the age. printf("Age set to: %d.\n", myHorse.age); Horse* pHorse = NULL; Horse aHorse = { 3, 11, "Jimbo", "Trigger", "Nellie"}; pHorse = &aHorse; printf("A horse's name is %s.\n", (*pHorse).name); printf("Same horse's name is %s.\n", pHorse->name); Family newKid = {"Joe", 5, "Bill", "Mary"}; Family oldKid = {"Jane", 15, "Bob", "Mary"}; if (siblings(newKid, oldKid)) printf("They are!\n"); if (siblingsWP(&newKid, &oldKid)) printf("They are too!\n"); while (true) wait(3600.0f); // Loop forever when done. } bool siblings(Family member1, Family member2) // Define the function. { bool maternal = strcmp(member1.mother, member2.mother); bool paternal = strcmp(member1.father, member2.father); return maternal || paternal; } // Passing pointers to large structs can save time and memory. bool siblingsWP(Family const *pMember1, Family const *pMember2) { // const refers to changing field content. bool maternal = strcmp(pMember1->mother, pMember2->mother); bool paternal = strcmp(pMember1->father, pMember2->father); return maternal || paternal; }