C - Structure Dynamic Memory Allocation

Description

Structure Dynamic Memory Allocation

Demo

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>                    // For malloc()

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

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

int main(void)
{

  Dog *pdogs[50];                  // Array of pointers to structure
  int hcount = 0;                      // Count of the number of dogs
  char test = '\0';                    // Test value for ending input

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

    // allocate memory to hold a dog structure
    pdogs[hcount] = (Dog*)malloc(sizeof(Dog));

    printf_s("Enter the name of the dog: ");
    scanf_s("%s", pdogs[hcount]->name, sizeof(pdogs[hcount]->name));

    printf_s("How old is %s? ", pdogs[hcount]->name);
    scanf_s("%d", &pdogs[hcount]->age);

    printf_s("How high is %s ( in hands )? ", pdogs[hcount]->name);
    scanf_s("%d", &pdogs[hcount]->height);

    printf_s("Who is %s's father? ", pdogs[hcount]->name);
    scanf_s("%s", pdogs[hcount]->father, sizeof(pdogs[hcount]->father));

    printf_s("Who is %s's mother? ", pdogs[hcount]->name);
    scanf_s("%s", pdogs[hcount]->mother, sizeof(pdogs[hcount]->mother));
  }

  // Now tell them what we know.
  printf_s("\n");
  for (int i = 0; i < hcount; ++i)
  {
    printf_s("%s is %d years old, %d hands high,",
      pdogs[i]->name, pdogs[i]->age, pdogs[i]->height);
    printf_s(" and has %s and %s as parents.\n", pdogs[i]->father,
      pdogs[i]->mother);
    free(pdogs[i]);
  }
  return 0;
}

Result

The declaration:

Dog *pdogs[50];                   // Array of pointers to structure

defines only 50 pointers to structures of type Dog.

The following code inside the for loop allocate memory for each dog structrue variable.

pdogs[hcount] = (Dog*) malloc(sizeof(Dog));