structure can be defined as a
user defined data type that contains a range of other data types . we can say
that it is a composite type
lets see example of a structure
of a book database
struct structure_name
{
Char title[30];
Char author[30];
Int page;
};
So we can see that the structure starts with a struct keyword
followed by the structure name and then we have the different fields of the
structure or data type declared
Individual fields of a structure can be assessed by the dot operator
We can declare other variable of the structure we have made
For example
struct employee //structure defination
{
char name[20];
float salary;
int age;
}
main()
{
struct employee
emp1,emp2; // structure variable declaration
emp1.age = 28;
//assigning vale to the age field of the structure
printf(" age is %d \n",emp1.age); //printing
the structure field content
getch();
}
In this example we first define
the body of the structure above the main
function , then we declare some variable of the structure type and then we use
the dot operator with the structure variable to assign value to one of the
field of the structure , and last we display the content of the structure
We can pass structure to a function just like any other variable
Function( employee) //
passing a structure variable employee to a function
Function_2(struct employee employee2) // accepting the passed value
{
printf(“%d”,employee2.age);
}
We can also return a structure
like this
employee1 = read_enployee();
The function look likes this
read_employee()
{
struct employee emp
scanf(“%d”,&emp.age);
return emp;
}
No comments:
Post a Comment