C Language / Structures and Unions

It is used to group different data types into a single data type. i.e user defined data type.

Structure Syntax
struct structureName / Tag Name
{
dataType member1;
dataType member2;
...
};

Note
Structure members are accessed using dot (.) operator.

Create emp structure with 3 members (name, dept and salary), initialize and print. Output

#include<stdio.h>
#include<string.h>

struct emp
{
char name[25];
char dept[10];
int salary;
};

int main()
{
struct emp strobj;
strobj.salary = 99999;
strcpy(strobj.name, "Wisdom Materials");
strcpy(strobj.dept, "Software");

printf("Employee Details\n");
printf("Employee Name: %s\n", strobj.name);
printf("Employee Department: %s\n", strobj.dept);
printf("Employee Salary: %d\n", strobj.salary);
}

Employee Details
Employee Name: Wisdom Materials
Employee Department: Software
Employee Salary: 99999<
Explanation
structure object= Strobj
structure members= name, dept and salary

Structure pointer
For a Structure we create a pointer called as Structure pointer. Structure pointer accesses members using arrow (->) operator.

Program Output

#include<stdio.h>
#include<string.h>

struct emp
{
char name[25];
char dept[10];
int salary;
};

void main()
{
struct emp strobj;
struct emp *strptr= &strobj;
strobj.salary = 99999;
strcpy(strobj.name, "Wisdom Materials");
strcpy(strobj.dept, "Software");
// Accessing structure members using structure pointer
printf("Employee Details\n");
printf("Employee Name: %s\n", strptr->name);
printf("Employee Department: %s\n", strptr->dept);
printf("Employee Salary: %d\n", strptr->salary);
}

Employee Details
Employee Name: Wisdom Materials
Employee Department: Software
Employee Salary: 99999

Explanation
structure object= Strobj
structure members= name, dept and salary
structure pointer = strptr

Unions
Structures are similar to unions in terms of operation and keyword differs.

Structures Union
Each member has assigned unique storage area of location. All members share same storage area of location.
All members can be accessed at a time. Individual members can be accessed at a time.


Home     Back