What is Structure in C Language
Categories: C language
Structure in c is a user-defined data type that enables us to store the collection of different data types. Each element of a structure is called a member. Structures ca; simulate the use of classes and templates as it can store various information
The ,struct keyword is used to define the structure. Let's see the syntax to define the structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Let's see the example to define a structure for an entity employee in c.
struct employee
{ int id;
char name[20];
float salary;
};
Declaring structure variable
We can declare a variable for the structure so that we can access the member of the structure easily. There are two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.
1st way:
Let's see the example to declare the structure variable by struct keyword. It should be declared within the main function.
struct employee
{ int id;
char name[50];
float salary;
};
Now write given code inside the main() function.
struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2 can be treated in the same way as the objects in C++ and Java.
2nd way:
Let's see another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
Which approach is good
If number of variables are not fixed, use the 1st approach. It provides you the flexibility to declare the structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in main() function.
1. Accessing members of the structure
2. There are two ways to access structure members:
By . (member or dot operator)
By -> (structure pointer operator)
Let's see the code to access the id member of p1 variable by. (member) operator.
p1.id