Structure in C – Part 1

By | February 9, 2015
So far I told you about the data types which can store only one type of data. E.g. int can only store integers, char can only store characters and so on. But in real life programming we hardly find some data which can be stored by using only one data type. Suppose we want to store the information of a student in a school. His information may contain his name which will be a string, his class which will be integer, his marks which will be float and so on.

Obviously we can also use arrays to store this information but it would be inefficient if I want to store information of 1000-2000 students. So basically we need a data type which can store values of dis-similar types. We need a data type which can be used to access those dis-similar type values easily. To solve this problem the concept of structures was introduced. So today I will give a basic overview of structure, its declaration and initialization.

Structure in C

Structure is the user defined data type that hold variables of different data types. Basically it gives a common name to the collection of different data types. We can also say that structure is a collection of dissimilar type of elements.

Defining a Structure

We have to define a structure first before using it. Given below is one example that will show how structure is defined.

Here struct is keyword and student is the name of structure. name, marks and roll_no are the elements of this structure. You can clearly see that all these elements are of different data type. Remember declaration of structure does not reserve any space in memory.

Declaring Structure Variables

Look below code that will declare structure variables.

Here s1, s2 and s3 are student type variables. We can also declare structure variables while defining the structure. This is shown in below example.

Structure Initialization

In the above code a1 and a2 are the structure variables. Consider carefully I have stored name, price and pages one by one.

Tips while using Structure in C

  • Generally people forget to write semi colon at the end of closing brace of structure. It may give some big errors in your program. So write semi colon every time at the end of structure definition.
  • Usually people declare structure variables at the top of the program. While making some big programs, programmers prefer to make separate header file for structure declaration. They include them at the beginning of the program.

Leave a Reply

Your email address will not be published. Required fields are marked *