C – Structure

What is a structure?

Structure is the group of heterogeneous data structure which can store data of different data types or Structure is a collection of variables of different types under a single name. In the case of array, we can store the data of same data type but what if we have to save data of different data type in structure. Can use single structure name for  more type of data in structure and union. Storage area is not reserved by the compiler to structure definition.

  • Keyword struct  is used for creating a structure.
  • Structure is a user defined data structure.

Structure Syntax :

 

How to create a structure?

‘struct’ keyword is used to create a structure. Following is an example.

Rules

  • Use declare semicolon  };at end of structure. (Don’t forget the semicolon in  the ending line.)

 

How to declare structure variables?

Way 1:

Way 2 : struct struct_name var_1, var_2;

  • Referencing structure members :  struct_var-name . member_variable
  • A structure variable can be assigned to other using =, but cannot be compared with other using ==
  • In Structure bit cant set in float variable.

 

How to initialize structure members?

Note : Structure elements cannot be initialized. When we declare a structure or union, we actually declare a new data type suitable for our purpose.

So we cannot initialize values as it is not a variable declaration but a data type declaration. The below program output is Compilation error.

 


Cannot have static members

In C, struct and union types cannot have static members. In C++, struct types are allowed to have static members, but union cannot have static members in C++ also. The Below program output is compilation error

 


Example

In a school we need to store data like name, roll no, address and percentage. But we are able to store only one data type at a time. So, C programming provides structure data type which can store data of different types such as integer, float, character etc. In the case of above school, we can initialize structure as :

 


Nested structure [structure with structure]

  • A structure containing an element of another structure as its member is referred so.


What is a self-referential structure?

  • A structure containing the same structure pointer variable as its element is called as self-referential structure.

When to user ->  (arrow) operator.

  • If the structure/union variable is a pointer variable, to access structure/union elements the arrow operator is used.

Array of structure :Syntax : struct structure_name var_name [size];

 



Reference

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

if you have any queries call us +918300026060 or WhatsApp Dismiss

0

Your Cart

%d bloggers like this: