C - Structure Structure Array

Description

Structure Array

Demo

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <ctype.h>

typedef struct Dog Dog;            // Define Dog as a type name

struct Dog                           // Structure type definition
{
  int age;/*from   w ww . j  av a 2 s  . com*/
  int height;
  char name[20];
  char father[20];
  char mother[20];
};

int main(void)
{
  Dog my_dogs[50];                 // Array of Dog elements
  int dog_Count = 0;                      // Count of the number of dogs
  char test = '\0';                    // Test value for ending

  for (dog_Count = 0; dog_Count < sizeof(my_dogs) / sizeof(Dog); ++dog_Count)
  {
    printf_s("Do you want to enter details of a%s dog (Y or N)? ",
      dog_Count ? "nother" : "");
    scanf_s(" %c", &test, sizeof(test));
    if (tolower(test) == 'n')
      break;

    printf_s("Enter the name of the dog: ");
    scanf_s("%s", my_dogs[dog_Count].name, sizeof(my_dogs[dog_Count].name));

    printf_s("How old is %s? ", my_dogs[dog_Count].name);
    scanf_s("%d", &my_dogs[dog_Count].age);

    printf_s("How high is %s ( in hands )? ", my_dogs[dog_Count].name);
    scanf_s("%d", &my_dogs[dog_Count].height);

    printf_s("Who is %s's father? ", my_dogs[dog_Count].name);
    scanf_s("%s", my_dogs[dog_Count].father, sizeof(my_dogs[dog_Count].father));

    printf_s("Who is %s's mother? ", my_dogs[dog_Count].name);
    scanf_s("%s", my_dogs[dog_Count].mother, sizeof(my_dogs[dog_Count].mother));
  }
  // Now tell them what we know.
  printf_s("\n");
  for (int i = 0; i < dog_Count; ++i)
  {
    printf_s("%s is %d years old, %d hands high,",
      my_dogs[i].name, my_dogs[i].age, my_dogs[i].height);
    printf_s(" and has %s and %s as parents.\n", my_dogs[i].father,
      my_dogs[i].mother);
  }
  return 0;
}

Result

The following code creates a Dog array.

Dog my_dogs[50];                // Array of Dog elements

This declares the variable my_dogs to be an array of 50 Dog structures.

You have a for loop controlled by the variable dog_Count:

for(dog_Count = 0 ; dog_Count < sizeof(my_dogs)/sizeof(Dog) ; ++dog_Count)
{
  ...
}

Related Topics

Exercise