Structure in C Language || C Tutorials
×


Structure in C

11319

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.

The 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 in C

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 in C

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 the employee i.e. all the structure variables 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 the 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

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.

Example:

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



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments