Friday, January 27, 2012

Structure in c programming

A introduction
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 {
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

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


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.stock,      p1.price,p1.dis);

No comments:

Post a Comment