The Basics

Structures are one of the fundamental building blocks of the C language. They allow you to create a block of information that can contain any combination of data types, even user defined data types and other structures.

The most common use for structures is abstract data types such as linked lists, queues, and stacks.



So how do you create a structure? It's quite simple, actually. The definition is as follows:

struct name{

Let's say you are a teacher, and you want to create a database that contains grade information for your students. You want a integer value for the student number, and float variables for the grades. So, let's say there are three tests during the semester. You could define a structure as follows:

struct grades{
  int stud_num;
  float test1;
  float test2;
  float test3;

Now you have defined a structure called 'grades'. Remember that this is only a definition, you have not allocated any storage space for a structure yet. So now you want to use the structure you just created. First you have to declare a variable of type 'struct grades'.

struct grades student1;

This statement creates a variable named student1. The variable itself is actually a structure, and that structure contains one integer variable, and three float variables.

The next thing you want to do, is assign values for the different elements of the structure. To do this, you use the 'dot operator' (.) to access individual members of the structure:

student1.stud_num = 1029516;
student1.test1 = 94.0;
student1.test2 = 85.5;
student1.test3 = 91.0;

These statements show access to the elements of a structure. You just use the name of the declared variable (not the defined structure name), then a period, then the name of the element you wish to access. Following this convention, calculating the average should be easy:

float average1;
average1 = (student1.test1 * student1.test2 * student1.test3) / 3;

As you will see in later sections, by combining structures with pointers, you can create very powerful (and often very confusing) linked data structures.




Copyright 1995-1997, Reality˛ Design