Structures in C


Why structure ?



1.  Array can be used to represent multiple data items of same datatype.But to represent data items of different dataypes we use a structure.

Suppose you want to store data of an employee(id,name,salary,etc).If data about 10 such employees needs to be stored.You can use individual arrays for storing ids,other for names,other for salaries.But as number of parameters related to your employee increases this approach becomes more difficult to handle.Structure comes into picture here.

2.  Used to implement data structures like linked list,tree,etc


Syntax


1.  Declaring a structure

struct <structure name>
{
    datatype1 member1,...;
    datatype2 member2,...;
    ...
};
struct book
{
    int id;
    float price;
    char name[15];
};

struct keyword is used for structure declaration.

Structure definition does not tell the compiler to reserve any memory at compile time.When variable of this structure is declared the compiler comes to know the size of the variable at compile time and memory is allocated to it during execution.

2.  Declaring structure variables


Let b1,b2 be structure variables.
struct book
{
    int id;
    float price;
    char name[15];
}b1,b2;
struct
{
    int id;
    float price;
    char name[15];
}b1,b2;
struct book
{
        int id;
        float price;
        char name[15];
};
struct book b1,...;

See use of typedef keyword to declare structure here.


3.  Initializing struct variables

struct book
{
    int id;
    float price;
    char name[15];
}b1={1,250.75,"ABC"},b2={2,300.50,"XYZ"};
struct
{
    int id;
    float price;
    char name[15];
}b1={1,250.75,"ABC"},b2={2,300.50,"XYZ"};
struct book
{
    int id;
    float price;
    char name[15];
};
struct book b1 = {1,250.75,"ABC"};


Accessing structure members


Dot operator is used for this.To access id of b1 we use
b1.id
b1 is structure variable and id is data member of structure.


Storage of structure members


They are stored in contiguous memory locations.
    b1.id         b1.price       b1.name
_____________________________________________
|    1       |    250.75    |      ABC      |
|____________|______________|_______________|
    500            502            506


Copy a structure variable to other variable

b1 = b2


More






No comments:

Post a Comment