As we know Array is a collection of homogeneous data types. Same a structure is a collection of heterogeneous data types.
Suppose we want to keep records of an employee name, age, and his salary then how we will keep either define three different variable or define a structure which keeps all three variable under a single name. Not clear, No need to worry…. As we proceed this chapter things will be cleared.
Structure definition :
“struct” keyword is used to define a structure.
Syntax of a structure
struct structure-name
{
structure-member1;
structure-member2;
structure-member3
……………..
structure-memberN;
};
So, how to create a structure for an employee to keep record his name,
age and salary. See below
struct employee
{
char name[50];
int age;
float salary;
};
Here ‘struct employee’ is user defined data type and variable defined inside structure is called its member. Like “char name[50]”, “int age”, “float salary” are membranes of struct employee. Rememberer No memory is allocated for definition of structure.
Structure declaration :-
struct employee emp1;
struct employee emp2;
struct employee emp[10];
or we can declare structure like given below
struct employee emp1, emp2, emp[10];
or we can declare like
struct employee
{
char name[50];
int age;
float salary;
}emp1, emp2, emp[10];
Remember Memory is allocate for structure declaration only.
Now we will learn how to Access members of a structure. There are two ways to access members of a structure.
- Using member access ( . ) operator
- Using ” -> ” operator
An example program to show how to access members of structure using (.) dot operator.
#include <stdio.h>
#include <string.h>
struct employee
{
char name[50];
int age;
float salary;
};
int main()
{
struct employee record = {0}; /* Initializing to zero */
strcpy(record.name, “Gyan”);
record.age = 30;
record.salary = 30000;
printf(” Employee Name = %s \n”, record.name);
printf(“Employee age = %d \n”, record.age);
printf(” Employee salary = %d \n”, record.salary);
return 0;
}
Output:
Employee Name = Gyan
Employee age = 30
Employee salary = 30000
We will see how to access members of structure using “->” operator in next chapter structure and pointer