Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

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

int
main()
{
  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.
     

 
 
  Published under the terms of the GNU General Public License Design by Interspire