CS13002 Programming and Data Structures

Section 3/C, Spring 2003--2004

A primer on structures

So far you have seen only some built-in C data types to represent integers, floating point numbers, strings, arrays etc. C also provides facilities to join these primitive data types in order to construct compound user-defined data types.

The basic way to create compound objects is to use the construct struct, which is an abbreviation for `structure'. Its syntax is as follows:

typedef struct {
   /* Declaration of components */
} dataTypeName;

As an example suppose that we want to represent rational numbers, i.e., numbers of the form a/b with b>0. A structure of two integer components can be used:

typedef struct {
   int numerator;
   unsigned int denominator;
} rational;
One can declare rational variables in the usual way:
rational rat1, rat2, ratArray[20];
In order to access the individual components of a rational variable, one writes the variable name followed by a dot followed by the component name. For example, rat1.numerator denotes the first component (an int) of the structure rat1. Similarly ratArrat[3].denominator represents the second component (an unsigned int) of the 3rd element of the array ratArray.

Functions may input and output structure variables. As an example, the function that computes the sum of two rational numbers may be written as follows:

rational ratSum ( rational rat1 , rational rat2 )
{
   rational sum;

   sum.denominator = rat1.denominator * rat2.denominator;
   sum.numerator = rat1.numerator * rat2.denominator;
   sum.numerator += rat2.numerator * rat1.denominator;

   return(sum);
}

...

main ()
{
   rational rat1, rat2, rat3;

   rat1.numerator = 4; rat1.denominator = 3;
   rat2.numerator = 3; rat2.denominator = 4;
   rat3 = ratSum(rat1,rat2);
   printf("%d/%u + %d/%u = %d/%u\n",
           rat1.numerator, rat1.denominator,
           rat2.numerator, rat2.denominator,
           rat3.numerator, rat3.denominator);
}
This program prints:
4/3 + 3/4 = 25/12

A structure may contain arrays and other structures. For example, the following defines a polynomial with real coefficients:

#define MAX_DEG 1000
typedef struct {
   int degree;
   double coefficient[MAX_DEG];
} poly;
...
poly f, g, h;
If f is a poly structure, f.degree refers to the degree of the polynomial it is representing, whereas f.coefficient[i] its i-th coefficient (i.e., the coefficient of Xi).

Finally, here is a nesting of structures:

typedef struct {
   char name[512];
   unsigned int age;
   char homeAddress[1024];
   float height;
} human;

typedef struct {
   human generalRecords;
   char department[64];
   char rollNumber[8];
   float CGPA;
} student;

student stud1, stud2;
student section3Studs[87];
Then stud1.CGPA, section3Studs[55].generalRecords.height etc. are some of the individual components.


Lab home