In C, you can create your own data types; in the next section you will see that FILE is an example of this. A "structure" is a collection of one or more variables which are grouped together under a single name; in other languages these are sometimes called "records". There are two keywords which you will use when creating structures:

  • struct -- used to describe a new data type
  • typedef -- used to associate a name to the struct or another type

This example, which you might find in computer graphics, creates a structure to hold a pair of 2D coordinates to define a line.

Example struct statement:

In the above example, a variable called "line1" is defined to be of type line, as defined in the structure above.

Typedef associates a name with the structure; this should typically appear at the start of the program.

To access the individual parts of a variable of a structure, use the "dot notation".

This notation can also be used to evaluate conditionals:

Structures can also be passed and returned from functions; just be sure that the function prototype comes after the structure is declared.

Structures should be used to make programming easier, and to make it easier for other programmers to read your code. Library writers often use structs to define and maintain a clean interface to their library. A user of said library should then be able to interact with it simply by understanding the interface struct (and the associated comments which should always go with it!).

Another example: a struct for defining complex numbers
Pointers to Structs

As with any datatype in C, it can frequently be useful to work with pointers to structs. This is very similar to what has already been discussed in the section on pointers, but it is useful to see how to reference members of a struct when we have a pointer to it. Using the above line example, we can use -> instead of . to access the structure"s members:

 
©   Cornell University  |  Center for Advanced Computing  |  Copyright Statement  |  Inclusivity Statement