C - Structure Structure Members

Introduction

To access struct member, use the dot notation. Suppose we have the following definition.

struct Dog
{
  int age;
  int height;
  char name[20];
  char father[20];
  char mother[20];
};

struct Dog d1 = {4, 7,"A", "B", "C"};

You can access the age member as

d1.age = 12;

You can specify the member names in the initialization list, like this:

d1 = {.height = 15, 
      .age = 30,
      .name = "A", 
      .mother = "B", 
      .father = "C"
};

Demo

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>

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

struct Dog                           // Structure type definition
{
  int age;/*from   ww w.  j  av a2s .  c om*/
  int height;
  char name[20];
  char father[20];
  char mother[20];
};

int main(void)
{
  Dog my_dog;                      // Structure variable declaration

  // Initialize  the structure variable from input data
  printf_s("Enter the name of the dog: " );
  scanf_s("%s", my_dog.name, sizeof(my_dog.name));     // Read the name

  printf_s("How old is %s? ", my_dog.name );
  scanf_s("%d", &my_dog.age );                           // Read the age

  printf_s("How high is %s ( in hands )? ", my_dog.name );
  scanf_s("%d", &my_dog.height );                        // Read the height

  printf_s("Who is %s's father? ", my_dog.name );
  scanf_s("%s", my_dog.father, sizeof(my_dog.father)); // Get pa's name

  printf_s("Who is %s's mother? ", my_dog.name );
  scanf_s("%s", my_dog.mother, sizeof(my_dog.mother)); // Get ma's name

  // Now tell them what we know
  printf_s("%s is %d years old, %d hands high,",
                                 my_dog.name, my_dog.age, my_dog.height);
  printf_s(" and has %s and %s as parents.\n", my_dog.father, my_dog.mother);
  return 0;
}

Result

Related Topics

Exercise