Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 14

Structures and Union

To represent a collection of data items of different types using a single name.

Why Structure
We have seen that arrays can be used to represent a group of data items that belong to the same type,such as int or float.

However we can not use an array if we want to represent a collection of data items of different types using a single name.
That can be done using structure.

What is Structure
A structure in C is a heterogeneous user defined data type.It groups variables into a single entity. A structure is a convenient tool for handling a group of logically related data items.

What is Structure
Arrays stores homgenous data where structuer can hold heterogeneous data. Unlike arrays, structures must be defined first fo their format that may be used later to declare structure variables.

Structure Declaration
struct student { char name[25]; int age ; float marks; }; Above declaration groups name,age and marks into a single entity student.

struct is a reserved word. student is called structure tag or simply tag.This is the name of the structure
NB: NO MEMORY IS ALLOCATED SO FAR.

A new Type is defined by the Programmer


student is a new type defined by the user,which can
hold heterogenous data.
To use this structure student in a program we must create a variable of type student as follows:

struct student x;
Always remember to give the keyword struct before the structure name while creating a variable.

x is a variable of type student.


just like int z; z is a variable of type integer.

Using structure variable


#include<stdio.h> #include<conio.h> main() { struct student { char name[25]; int age; float marks; }; struct student x;

Using structure variable


clrscr(); printf("Enter name: "); scanf("%s",x.name); printf("Enter age : "); scanf("%d",&x.age); printf("Enter marks:"); scanf("%f",&x.marks);

printf(" \n\nName :%s \n Age :%d \n Marks:%.2f",x.name,x.age,x.marks); getch();


}

Array of Structures
To maintain information about 10 students,declare an array of student structure. struct student x[10];

To store age of first student we write x[0].age=27;

Pointers to structure
struct student x,*ptr; ptr=&x; ptr->age=27;

A Program

Unions
A union is a user defined data type in C which allows the overlay of more than one variable in the same memory area. For example if a string of 200 bytes called filename is required by first 50 lines of the code only and another string called output of 400 bytes is required by the rest of the code(i.e both strings not needed simultaneouly),it would be waste of time to declare separate arrays of 200 and 400 bytes

You might also like