Structures are a way of storing many different values in variables of potentially different types under the same name. This makes it a more modular program, which is easier to modify because its design makes things more compact. Structs are generally useful whenever a lot of data needs to be grouped together--for instance, they can be used to hold records from a database or to store information about contacts in an address book. Structures in C are used to encapsulate, or group together different data into one object.
The format for defining a structure is
struct Tag {
Members
};
Where Tag is the name of the entire type of structure and Members are the variables within the struct. To actually create a single structure the syntax is
struct Tag name_of_single_structure;
To access a variable of the structure it goes
name_of_single_structure.name_of_variable;
For example:
struct example {
int x;
};
struct example an_example; //Treating it like a normal variable type
an_example.x = 33; //How to access it's members
Structure may come in two flavor
1)Singe structure
2)Nested structure(Sometime called structure within structure)
The variables which are declared inside the structure are called as 'members of structure. Structure variables are allocated in contagious memory location in memory. Structure name contain the base address of allocated space .And total structure space is nothing but the sum of individual size of member.
A sample program of structure
#include<stdio.h>
#include<conio.h>
struct product
{
char name[30];
int stock;
float price, dis;
};
void main()
{
struct product p1 ={"Apple iPod Touch 32GB", 35,298.56, 2.32};
clrscr();
printf("Name=%s,\nStock=%d,\nPrice=$%.2f,\nDiscount=%.2f%.", p1.name, p1.stock, p1.price,p1.dis);
getch();
}
No comments:
Post a Comment