6.8. Structured Data

In C you can create a new type e.g. ``Person''. Person can store an int called ``age'', a string called ``name'' and another int called ``height_in_cm''. Here's the code to make this new type:

struct Person
  char[40] name;
  int age;
  int height_in_cm;

This code creates a variable called struct Person. You can declare variable and pointers to variables of this type in the usual way. Say you declared a variable john of type struct Person. To access the ``age'' field you would use john.age. I'll make this clearer with a quick example using the previous definition of struct Person:

Example 6-4. person_struct.c

  struct Person hero = { 20, "Robin Hood", 191 };
  struct Person sidekick;

  john.age = 31;
  john.name = "John Little"
  john.height_in_cm = 237;

  printf("%s is %d years old and stands %dcm tall in his socks\n",
         sidekick.name, sidekick.age, sidekick.height_in_cm);

  printf( "He is often seen with %s.\n", hero.name );

  return 0;

When compiled and executed this will display:

John Little is 31 years old and stands 237cm tall in his socks
He is often seen with Robin Hood.