Introduction
Structure in C is a collection of one or more variable types. As you know, each element in an array must be the same data type, and you must refer to the entire array by its name. Each element (called a member) in a structure can be a different data type.
Usually, a structure is declared first followed by the definition of a structure variable as shown below:
Defining Structures
To define a C structure, you must use the struct statement. The struct statement defines a new data type, with more than one member, for your program. The format of the struct statement is this:
struct [structure tag/name] { member definition; member definition; : member definition; } [one or more structure variables];
/* declaration of a structure */
struct book { char name[20] ; int numpages ; float price ; } ;
struct book b ;
A structure variable can be initialized at the same place where it is being defined, as in
struct book b = { "C", 425, 135.00 } ;
Declaration of a structure and definition of a structure variable can be combined into one. When this is done mentioning the structure name is optional.
struct { char name[20] ; int numpages ; float price ; } book = { "C", 425, 135.00 } ;
Question: What is the size of the book in the above struct?
Answer: The size of a structure variable is the sum of the sizes of its individual elements. For example, size of b is: 20 + 2 + 4 = 26 bytes.
struct book { char name[20] ; int numpages ; float price ; } ; struct book b = { "Basic", 425, 135.00 } ; printf ( "%u %u %u", b.name, &b.numpages, &b.price ) ;
Elements of a structure are stored in adjacent memory locations.
For example, the following program would produce the output 5001, 5021, and 5023.
Each structure you define can have an associated structure name called a structure tag. Structure tags are not required in most cases, but it is generally best to define one for each structure in your program. The structure tag is not a variable name. Unlike array names that reference the array as variables, a structure tag is just a label for the structure’s format.