Structure in C
What is a structure?
A structure is a user defined data type in C. A structure creates a data type
that can be used to group items of possibly different types into a single type.
Syntax:
s struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example:
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:
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;
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;
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:
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;
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;
Accessing members of the structure
There
are two ways to access structure members:
1.
By
. (member or dot operator)
2.
By
-> (structure pointer operator)
1.
Simple
Program of structure
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
} e1;
int main( )
{
e1.id=101;
strcpy(e1.name, "pramod dwivedi
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
} }
Output:
employee 1 id : 101
employee 1 name : pramod dwivedi
There
are two ways to access structure members:
1.
By
. (member or dot operator)
2.
By
-> (structure pointer operator)
1.
Simple Program of structure
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
} e1;
int main( )
{
e1.id=101;
strcpy(e1.name, "pramod dwivedi
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
} }
Output:
employee 1 id : 101
employee 1 name : pramod dwivedi
No comments:
Post a Comment