Structure and union in c

Structure and union in c

Structure and union in c

In this tutorial, We start with new topic of c which is Structure and union in c.

Structures

Structure is user defined data type.

Structure is collection of elements of different type.

It is used to store values of different type of variable.

Declaration of structure

Syntax : –

12345678910111213struct <struct_name>{<Datatype>. member1;<Datatype>. Member2;.<Datatype>. Member n;};

In above syntax, struct is a keyword and <struct_name> is name given to the structure and in structure we declare different types of variable.

Memory allocated to structure is according to member in structure.

Size of the structure is equal to sum of memory allocated to all members in structure.

We create struct object as follows

    struct <Struct_name>  variblr_name;

Accessing structure members

We can access members of structure using dot operator which is shown below

     <struct_variable> . Member_name;

Array of structure

We can declare array of structure variable.We can create array of structure as follows

Syntax :-

     struct <struct_name> array_name[size];

We can access individual member of structure by a[i] where a is array name and i is index .

Structure with pointer

A pointer variable can used in structure to point and process that data.

To access the structure member the arrow operator is used as ->

Syntax :- <structure_pointer> -> structure_member;

Union

like a structure Union also used to store the elements of different types.

Difference between the structure and union is , in structure all members in structure has its memory location but in union members use same locations for storage.

Syntax :-

123456789101112131415union <union_name>{<Datatype>. member 1;<Datatype>. Member 2;..<Datatype>. Member n;} Variable_name;

Program to illustrate structure in c

123456789101112131415161718192021222324252627282930313233#include<stdio.h>struct technical{ int no; char name[30];};void main(){ struct technical s; printf(“Enter Number:”); scanf(“%d”,&s.no); printf(“Enter Name:”); scanf(“%s”,&s.name);printf(“\n************************\n”); printf(“\nNumber : %d”,s.no); printf(“\nName : %s”,s.name);}

Output:-

Enter Number:

10

Enter Name:

Technicalseek

Number : 10

Name : Technicalseek