• admin@embedclogic.com

Structure In C

Structure

Unlike an array, Structure is the collection of heterogeneous data type elements.

A structure is a secondary data type.unlike an array, it is used to collect different-2 data types element.

Syntax

where tag_name is optional.

structure_variable_Name is identifier through which you can access any member with dot(.) operator.

Example

Requirement: You want to save information of an employee in memory.

Employee Information:

Information DataType
Namestring(Array of char dataType)
employeIdunsigned int
Salarydouble

You have two option to save this info in memory –

— Declare the separate variables for each info.

— Use structure concept and store all heterogeneous info with a single identifier.

— I will prefer the second choice for smart programming-

empInfo: structure tag or name

emp: structure empInfo type variable.

Memory Map of Structure

Use of (.) operator

dot(.) operator is used by the structure identifier to access the members of a structure.

— emp.name=const_value1

— emp.empId=const_value2

— emp.salary=const_value3

Use of (->) Pointer operator

— emp->name=const_value1

— emp->empId=const_value2

— emp->salary=const_value3

Program

Output:

typedef use in Structure

typedef is used to give an alias name to the existing data type.Through the use of typedef, we can assign an alias name to the existing struct data type.

Program

Let’s apply typedef in above example –

Output

Nested structure

Nesting of structure means use of structure inside a structure.

Example

In above structure empBday  which is itself a structure is the member of another structure named empInfo .This process is called nesting of structure.

Program

Output

Structure in ‘C’

What is Structure?

In C language, an array is used to collect same data type values under a single variable name at contiguous memory locations but what happens if we need to collect different-2 datatype Values under the same roof. For example, you want to maintain the attendance record of employees of any company. Attendance record of an employee will contain following attributes

name         2. employeId           3. attendance

All above attributes of record need different-2 data type as shown in below table.

Information DataType
Namestring(Array of char dataType)
employeIdunsigned int
Salarydouble

So as we can see above all the members have the different-2 data type and if we initialize these individually then we can never get the right information of any employee because we don’t know where the requested field has stored. so in this situation, C gives a unique data type that will keep all the members [of same data type or heterogeneous data type] under the master data type which is called ‘struct‘ and concept is known as ‘structure’.

so ‘struct’ data type is secondary data type which is the collection of homogeneous or heterogeneous data types.

How to define it?

(more…)