Pointers to Structures - C Structure

C examples for Structure:Structure Definition

Description

Pointers to Structures

Demo Code

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

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

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

int main(void){
  Horse *phorses[50];                  // Array of pointers to structure
  int hcount = 0;                      // Count of the number of horses
  char test = '\0';                    // Test value for ending input

  for(hcount = 0 ; hcount < sizeof(phorses)/sizeof(Horse*) ; ++hcount)
  {
    printf("another (Y or N)? ");
    scanf(" %c", &test, sizeof(test));
    if(tolower(test) == 'n')
      break;

    // allocate memory to hold a horse structure
    phorses[hcount] = (Horse*) malloc(sizeof(Horse));

    printf("Enter the name of the horse: " );
    scanf("%s", phorses[hcount]->name, sizeof(phorses[hcount]->name));

    printf("How old is %s? ", phorses[hcount]->name );
    scanf("%d", &phorses[hcount]->age);

    printf("How high is %s ( in hands )? ", phorses[hcount]->name);
    scanf("%d", &phorses[hcount]->height);

    printf("Who is %s's father? ", phorses[hcount]->name);
    scanf("%s", phorses[hcount]->father, sizeof(phorses[hcount]->father));

    printf("Who is %s's mother? ", phorses[hcount]->name);
    scanf("%s", phorses[hcount]->mother, sizeof(phorses[hcount]->mother));
  }

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

Result


Related Tutorials