Professional Documents
Culture Documents
Structures and Union
Structures and Union
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.
struct student x;
Always remember to give the keyword struct before the structure name while creating a variable.
Array of Structures
To maintain information about 10 students,declare an array of student structure. struct student x[10];
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