Structure in C

by Yogesh Khanna 28-Aug-18

0 1784


The structure is also known as the collection of elements with different data types. We can store under a single name, multiple types of elements with different datatype can be saved.

First, we need to define a structure with different members and then by using that structure we need to declare that structure's variable. Structure variable has access to all the members of the given structure.


Steps needed to follow if anyone wants to implement the structure in the C programming language

1) Define Structure

2) Declare that structure variable

3) Initialize the members of that structure

4) Access the members of that variable


DEFINING A STRUCTURE

The syntax for defining any structure variable

Struct Tag name// tag name may be any name

{

Datatype1 variable name1;

Datatype2 variable name2;

.

.

.

.

};

Example (STRUCTURE DEFINITION):

struct employee

int number;

char name[5];

float Salary;

};


DECLARING STRUCTURE

The syntax for Structure declaration

struct Employee

int number;

char name[5];

float salary;

}

Struct Employee E1, E2;  >>>>>>>>>> Structure declaration

Here, we are declaring one structure variable, which should follow the structure of employee i.e. all the structure variable will be having all the data members.


INITIALIZATION

The structure can be initialized in 2 ways

1) Compile time

2) Run time

Compile time Initialization

We need to initialize each structured variable with the use of assignment operator.

Struct Employee E1= {30,"PQR", 85.78};

Struct Employee E2= {34,"STU",97.54};

For Run time Initialization

The structure can be initialized at the runtime with the help of Scanf

For Example:

Scanf("%d,%S,%F",&E1.number,E1.name,&E1.salary);


ACCESSING IN STRUCTURE

Accessing can be done with the help of the dot operator. With the use of dot, every structure variable can be able to access its member.

For example:

If E1 want to access the number then representation will be S1.number;


Share:


Discount Coupons



Comments

    Waiting for your comments

Leave a Reply