Structure in C


Prev Tutorial Next Tutorial

Structure in C

Structure is a user defined data type which hold or store homogeneous 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

ArrayStructure
1Array is collection of homogeneous data.Structure is the collection of heterogeneous data.
2Array data are access using index.Structure elements are access using . operator.
3Array allocates static memory.Structures allocate dynamic memory.
4Array element access takes less time than structures.Structure elements takes more time than Array.

Example of Structure

#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

Output: Enter employee Id, Name, Salary: 5 Spidy 45000 Id : 05 Name: Spidy Salary: 45000.00

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.


Prev Tutorial Next Tutorial

Advertisements




Facebook Likes

Advertisements