C Structures
Many programming tasks are simplified by the C data constructs called structures. A structure is a data storage method designed by you, the programmer, to suit your programming needs exactly.
- What simple and complex structures are
- How to define and declare structures
- How to access data in structures
- How to create structures that contain arrays and arrays of structures
- How to declare pointers in structures and pointers to structures
- How to pass structures as arguments to functions
- How to define, declare, and use unions
- How to use type definitions with structures
Simple Structures
A structure is a collection of one or more variables grouped under a single name for easy manipulation. The variables in a structure, unlike those in an array, can be of different variable types. A structure can contain any of C's data types, including arrays and other structures. Each variable within a structure is called a member of the structure. The next section shows a simple example.
You should start with simple structures. Note that the C language makes no distinction between simple and complex structures, but it's easier to explain structures in this way.
Defining and Declaring Structures
If you're writing a graphics program, your code needs to deal with the coordinates of points on the screen. Screen coordinates are written as an x value, giving the horizontal position, and a y value, giving the vertical position. You can define a structure named coord that contains both the x and y values of a screen location as follows:
struct coord {
int x;
int y;
};
The struct keyword, which identifies the beginning of a structure definition, must be followed immediately by the structure name, or tag (which follows the same rules as other C variable names). Within the braces following the structure name is a list of the structure's member variables. You must give a variable type and name for each member.
The preceding statements define a structure type named coord that contains two integer variables, x and y. They do not, however, actually create any instances of the structure coord. In other words, they don't declare (set aside storage for) any structures. There are two ways to declare structures. One is to follow the structure definition with a list of one or more variable names, as is done here:
struct coord {
int x;
int y;
} first, second;
These statements define the structure type coord and declare two structures, first and second, of type coord. first and second are each instances of type coord; first contains two integer members named x and y, and so does second.
This method of declaring structures combines the declaration with the definition. The second method is to declare structure variables at a different location in your source code from the definition. The following statements also declare two instances of type coord:
struct coord {
int x;
int y;
};
/* Additional code may go here */
struct coord first, second;
Accessing Structure Members
Individual structure members can be used like other variables of the same type. Structure members are accessed using thestructure member operator (.), also called the dot operator, between the structure name and the member name. Thus, to have the structure named first refer to a screen location that has coordinates x=50, y=100, you could write
first.x = 50;
first.y = 100;
To display the screen locations stored in the structure second, you could write
printf("%d,%d", second.x, second.y);
At this point, you might be wondering what the advantage is of using structures rather than individual variables. One major advantage is that you can copy information between structures of the same type with a simple equation statement. Continuing with the preceding example, the statement
first = second;
is equivalent to this statement:
first.x = second.x;
first.y = second.y;
When your program uses complex structures with many members, this notation can be a great time-saver. Other advantages of structures will become apparent as you learn some advanced techniques. In general, you'll find structures to be useful whenever information of different variable types needs to be treated as a group. For example, in a mailing list database, each entry could be a structure, and each piece of information (name, address, city, and so on) could be a structure member.
The struct Keyword
struct tag {
structure_member(s);
/* additional statements may go here */
} instance;
The struct keyword is used to declare structures. A structure is a collection of one or more variables (structure_members) that have been grouped under a single name for easy man-ipulation. The variables don't have to be of the same variable type, nor do they have to be simple variables. Structures also can hold arrays, pointers, and other structures.
The keyword struct identifies the beginning of a structure definition. It's followed by a tag that is the name given to the structure. Following the tag are the structure members, enclosed in braces. An instance, the actual declaration of a structure, can also be defined. If you define the structure without the instance, it's just a template that can be used later in a program to declare structures. Here is a template's format:
struct tag {
structure_member(s);
/* additional statements may go here */
};
To use the template, you use the following format:
struct tag instance;
To use this format, you must have previously declared a structure with the given tag.
Example 1 : Structure Declaration
/* Declare a structure template called SSN */
struct SSN {
int first_three;
char dash1;
int second_two;
char dash2;
int last_four;
}
/* Use the structure template */
struct SSN customer_ssn;
Example 2 : Structure Declaration
/* Declare a structure and instance together */
struct date {
char month[2];
char day[2];
char year[4];
} current_date;
Example 3 : Declare and initialize a structure
/* Declare and initialize a structure */
struct time {
int hours;
int minutes;
int seconds;
} time_of_birth = { 8, 45, 0 };
Example : A demonstration of structures that contain other structures.
1: /* Demonstrates structures that contain other structures. */
2:
3: /* Receives input for corner coordinates of a rectangle and
4: calculates the area. Assumes that the y coordinate of the
5: upper-left corner is greater than the y coordinate of the
6: lower-right corner, that the x coordinate of the lower-
7: right corner is greater than the x coordinate of the upper-
8: left corner, and that all coordinates are positive. */
9:
10: #include <stdio.h>
11:
12: int length, width;
13: long area;
14:
15: struct coord{
16: int x;
17: int y;
18: };
19:
20: struct rectangle{
21: struct coord topleft;
22: struct coord bottomrt;
23: } mybox;
24:
25: main()
26: {
27: /* Input the coordinates */
28:
29: printf("\nEnter the top left x coordinate: ");
30: scanf("%d", &mybox.topleft.x);
31:
32: printf("\nEnter the top left y coordinate: ");
33: scanf("%d", &mybox.topleft.y);
34:
35: printf("\nEnter the bottom right x coordinate: ");
36: scanf("%d", &mybox.bottomrt.x);
37:
38: printf("\nEnter the bottom right y coordinate: ");
39: scanf("%d", &mybox.bottomrt.y);
40:
41: /* Calculate the length and width */
42:
43: width = mybox.bottomrt.x - mybox.topleft.x;
44: length = mybox.bottomrt.y - mybox.topleft.y;
45:
46: /* Calculate and display the area */
47:
48: area = width * length;
49: printf("\nThe area is %ld units.\n", area);
50:
51: return 0;
52: }
Enter the top left x coordinate: 1
Enter the top left y coordinate: 1
Enter the bottom right x coordinate: 10
Enter the bottom right y coordinate: 10
The area is 81 units.
Read More Articles
- Use of getch(),getche() and getchar() in C
- Switch Case Statement Example Program In C Programming Language
- C Character Set
- Convert a Floating-point value to an Integer in C
- Data Input and Output gets and puts Example Program In C
- Special Operators In C
- Pointer Representation and Pointer Example Programs
- C Data Input and Data Output
- Simple While Loop Example Program In C Programming Language
- Data Output printf and putchar Example Program In C
- C Introduction
- C Operators
- Storage Classes In C
- C Pointers
- File Management
- C Identifiers
- Loop Control Statements
- Hello World - Simple C Program
- C Array
- Single Character Output Function : putchar()
- C Reserve Words
- C Specific Properties and Implementation
- If else Statement Example Program In C Programming Language
- If Statement Example Program In C Programming Language
- Confusing Array in C ( Array Representation and Initialization )