Structure in C programming

Structure in C

Structure in C is user defined data types. Before structure I had discussed about another user defined data types called array where we can store the data of same data types. Arrays cannot be used to store data of different data type.   Structure overcomes this problem. Structure is used to store data of different data types.

For example: If we need to store all information related to a student, it cannot be done by using array. We can store it using structure. Students has several data member such as name, roll, admission_no etc having different data types.

Syntax for declaring structure in C.

Declaration of structure in C is done with keyword struct followed by tag_name.

In the example you have observed closing braces in the syntax is followed by ; (semi colon) . Semi colon is mandatory in the structure.

Example:

In  the above example I have taken a structure named as student. The structure student has roll, admn and name as data member of type integer,integer and character array type respectively .

How to assign values to data member of structure ?

Values to data member of a structure can be assigned through the object of structure. Before going to above topic let us know about “how to create object of a structure ?”.

Object or copy of a structure can be made by two different ways:

1)At the time of structure declaration.

2)Inside main function.

First, object of a structure can be created at the time of structure declaration. Just after the ending of closing braces give the object name as you want to refer it, as shown below.

Above ‘s’ is a object of structure student.’s’ will have same data member as student has. So data member of student structure can be refereed via the object ‘s’.

Inside main function we can create object of a structure as we create variable of any data type.

So by following above syntax you can create the objects of structure.

Now the question arises how to assign values to data member of a structure?

As already said values can be assigned using the object of structure. Therefore look the complete program given below. You will come to know the method.

Program compiled in Dev C++ compiler.

OUTPUT:

Therefore, match the output with below program.

OUTPUT:


 

 

 

Leave a Reply