A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.
1. Declaring a Structure
The general form of a structure declaration statement is given below:
struct <structure name>
{
structure element 1;
structure element 2;
structure element 3;
......
......
structure element n;
};
Once the new structure data type has been defined one or more variables can be declared to be of that type.
For example the variables b1, b2, b3 can be declared to be of the type struct book,
as,
This statement sets aside space in memory. It makes available space to hold all the elements in the structure—in this case, 7 bytes — one for name, four for price and two for pages. These bytes are always in adjacent memory locations.
Like primary variables and arrays, structure variables can also be initialized where they are declared. The format used is quite similar to that used to initiate arrays.
2. Accessing Structure Elements
In arrays we can access individual elements of an array using a subscript. Structures use a different scheme. They use a dot (.
) operator. So to refer to pages
of the structure defined in book structure we have to use,
Similarly, to refer to price
we would use,
Note that before the dot there must always be a structure variable and after the dot there must always be a structure element.
3. Example
The following example illustrates the use of this data type.
And here is the output...
Enter names, prices and no. of pages of 3 books
A 100.00 354
C 256.50 682
F 233.70 512
And this is what you entered
A 100.000000 354
C 256.500000 682
F 233.700000 512
4. Structures as Function Arguments
You can pass a structure as a function argument in the same way as you pass any other variable.
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Book author : Developer Insider
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : C++ Programming
Book author : Developer Insider
Book subject : C++ Programming Tutorial
Book book_id : 6495700
5. Summary
- A structure is usually used when we wish to store dissimilar data together.
- Structure elements can be accessed through a structure variable using a dot (
.
) operator. - Structure elements can be accessed through a pointer to a structure using the arrow (
->
) operator. - All elements of one structure variable can be assigned to another structure variable using the assignment (
=
) operator. - It is possible to pass a structure variable to a function either by value or by address.
- It is possible to create an array of structures
6. Examples
Example Statement for Structure and Union in C Language |
---|
1. Calculate Size of Structure |
2. Use structure within union |
3. Find the size of a union |
Next - Files Handling