#include<stdio.h>/* Compile: cc -g -ansi -pedantic -Wall -O2 -o struct struct.c *//* Run: ./struct */intmain()
{
/* Define a couple of structs. */structperson
{
char *first_name;
char *last_name;
intage;
};
structpet
{
char *name;
intage;
};
/* Declare variables with a type of the defined structs. */structpersonelder_twin;
structpersonyounger_twin;
/* Define, declare, and initialize a (nested) struct variable in one single statement. */structperson_with_pet
{
char *first_name;
char *last_name;
intage;
structpetdog;
}
sister =
{
"Joan", "Jones", 42,
{
"Fido", 3
}
};
/* Define a pointer to a structure. */structperson_with_pet *pointer_to_sister;
structpet *pointer_to_dog;
/* Initialize a variable. */
elder_twin.first_name = "Jim";
elder_twin.last_name = "Jones";
elder_twin.age = 43;
/* Copy a struct variable. */
younger_twin = elder_twin;
/* Modify a struct member in an variable. */
younger_twin.first_name = "John";
/* Access struct elements. */
printf("The twins %s and %s %s are %i years old, and they have a sister.\n", elder_twin.first_name, younger_twin.first_name, younger_twin.last_name, younger_twin.age);
printf("Her name is %s %s, and she has a dog called %s, which is %i years old.\n", sister.first_name, sister.last_name, sister.dog.name, sister.dog.age);
/* Access struct elements using pointers. */
pointer_to_sister = &sister;
pointer_to_dog = &(pointer_to_sister->dog);
/* Different ways to access the same structure member. */
printf("%s is barking.\n", sister.dog.name);
printf("%s is barking.\n", (*pointer_to_sister).dog.name);
printf("%s is barking.\n", pointer_to_sister->dog.name);
printf("%s is barking.\n", pointer_to_dog->name);
/* Get rid of this annoying noise! */
printf("Please shut up, %s!\n", pointer_to_dog->name);
/* Always return something. */return 0;
}