Tuesday, 3 January 2012


A structure is collection of dissimilar data types.
A struct is an aggregate type, meaning that it is made up of other objects. 
The objects that make up a struct are called its members. 
The members of a struct may be accessed by the '.' or '->' operators. 
A struct may be named or unnamed.
We used variable in our C program to store value but one variable can store only single piece information (an integer can hold only one integer value) and to store similar type of values we had to declare many variables. 
To overcome this problem we used array which can hold numbers of similar data type. 
But array too have some limitations, like in our real world application we deal with set of dissimilar data types and single array cannot store dissimilar data.
For example think about storing book information or product information, a product can have different information to store like product code (an integer), product name (a char array), product price (a float) etc. 
And to store 20 products information we can declare integer array for product code, 2D character array for storing product name and float array to store product price. This approach definitely achieves your goals, but try to consider these things too. What if you wanted to add more products than 20, what if you want to add more information on products like stock, discount, tax etc? It will become difficult to differentiate these variables with other variables declared for calculation etc.
To solve this problem C language has a unique data type called Structure. 
C structure is nothing but collection of different related data types. 
If we are using C structure then we are combining different related data types in one group so that we can use and manage those variables easily. Here related data type means, a structure holding information about book will contains variable and array related to book.
Syntax for C Structure declaration
struct structure_name 

data type member1; 
data type member2; 
Example 1:
struct products 

char name[20];
int stock;
float price;
So structure declaration begins with struct keyword and with a space we need to provide a structure name. 
Within open and closed curly braces we can declare required and related variable, you can see it in our example structure declaration. 
And most important point to remember in case of C structure is that it ends with semicolon (;).
Example 2:
 struct product
    char name[30];
    int stock;
    float price, dis;
 void main()
struct product p1 ={"Apple iPod Touch 32GB", 35,298.56, 2.32}; 
printf("Name=%s,\nStock=%d,\nPrice=$%.2f,\nDiscount=%.2f%.", p1.name, p1.stock, p1.price,p1.dis);

No comments:

Post a Comment

host gator coupon