Introduction to structures in c

Structure is a user-defined datatype in C language which allows us to combine data of different types together. Structure helps to construct a complex data type which is more meaningful. It is somewhat similar to an Array, but an array holds data of similar type only. But structure on the other hand, can store data of any type, which is practical more useful.

Example

If I have to write a program to store Student information, which will have Student's name, age, branch, permanent address, father's name etc, which included string values, integer values etc, how can I use arrays for this problem, I will require something which can hold data of different types together.In structure, data is stored in form of records.

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.

struct student{ 
char name[10];
 int marks; 
int roll_no;
};

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.

struct student s1,s2,s3;

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.

 

struct student{
 char name[10]; 
int marks; 
int roll_no;
}s1,s2,s3;

Structure Initialization

struct book {
char  name[10] ; 
float  price ;
int  pages ;
 };
 struct book  a1={"MATH",190.00,210}; 
 struct book  a2={"ENGLISH",250.80,559};

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

 

POINTS TO REMEMBER-

  • 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.