Structure in C
Structure in C
Structure is a user defined data type which hold or store heterogeneous data item or element in a singe variable. It is a Combination of primitive and derived data type.
Why Use Structure in C
In C language array is also a user defined data type but array hold or store only similar type of data, If we want to store different-different type of data in then we need to defined separate variable for each type of data.
Example: Suppose we want to store Student record, then we need to store....
- Student Name
- Roll number
- Class
- Address
For store Student name and Address we need character data type, for Roll number and class we need integer data type.
If we are using Array then we need to defined separate variable.
Example
char student_name[10], address[20]; int roll_no[5], class[5];
If we use Structure then we use single variable for all data.
Syntax
struct stu { char student_name[10]; char address[20]; int roll_no[5]; int class[5]; };
Note: Minimum size of Structure is one byte and Maximum size of Structure is sum of all members variable size.
Note: Empty Structure is not possible in C Language.
Defining a Structure
Syntax
struct tagname { Datatype1 member1; Datatype2 member2; Datatype3 member3; ........... };
At end of the structure creation (;) must be required because it indicates that an entity is constructed.
Example
struct emp { int id; char name[36]; int sal; }; sizeof(struct emp) // --> 40 byte (2byte+36byte+2byte)
Syntax to create structure variable
struct tagname variable;
Difference Between Array and Structure
Array | Structure | |
---|---|---|
1 | Array is collection of homogeneous data. | Structure is the collection of heterogeneous data. |
2 | Array data are access using index. | Structure elements are access using . operator. |
3 | Array allocates static memory. | Structures allocate dynamic memory. |
4 | Array element access takes less time than structures. | Structure elements takes more time than Array. |
Example of Structure in C
#include<stdio.h> #include<conio.h> struct emp { int id; char name[36]; float sal; }; void main() { struct emp e; clrscr(); printf("Enter employee Id, Name, Salary: "); scanf("%d",&e.id); scanf("%s",&e.name); scanf("%f",&e.sal); printf("Id: %d",e.id); printf("\nName: %s",e.name); printf("\nSalary: %f",e.sal); getch(); }
Output
Syntax to access structure members
By using following operators we can access structure members.
Syntax
. struct to member --> pointer to member
When the variable is normal type then go for struct to member operator.
When the variable is pointer type then go for pointer to member operator.
Difference Between Structure and Pointer in C
Structure in C refer to a collection of various data types for example you create a structure named "Student" which contains his name , roll no, DOB etc. Name is string, Roll no is int.
While pointer refer to address in C & symbol are used to point some particular place in C memory.