C Programming/Structs

Objective

 * Learn about structs and how to use them.
 * Declaring structs.
 * Defining structs.

Introduction
Structures allow objects of different types to be stored within one object. Let's say that you want to store a car's colour, maximum speed and registration number. We can define a structure that includes all that information.

First, include the header files required for  and  :

Define the structure:

Example of the structure being used:

Dynamic Structures
Along with being static, structures can also be dynamic. This means that they can be created and deleted at run time. An example is given below. OUTPUT This is a American Eskimo dog. The American Eskimo's name is Foxtrot. Foxtrot has a nice white coat. Foxtrot is 6 years old.

This is a German Shepherd dog. The German Shepherd's name is Delta. Delta has a nice tan with a black saddle coat. Delta is 3 years old.

This is a Tamaskan dog. The Tamaskan's name is Whiskey. Whiskey has a nice wolf grey coat. Whiskey is 2 years old.

It is now possible to do dynamic things with each  structure, although those operations could be a little advanced. Also notice the use of the arrow operator. This is a cleaner way of using pointers when working with structures. For example  is equal to. The arrow operator makes it easier when accessing nested structures.

Assignments



 * Previous Lesson: Strings
 * Next Lesson: Input and Output
 * Course Home Page