Ads block

Banner 728x90px

Structure

Structure is same as an array but has some differences in its syntax. An array is a collection of similar/same type of elements but we can see that in many real life applications we may need to group different types of logically related data and this data may be an integer, may be a character or may be float number.

For example if we want to create a record of a person that contains name, age and height of that person, that we can't use array because all the three data elements are of different types.

To store these related infomations of different data types we can use a structure, which is capable of storing heterogeneous data.

Data of different types can be grouped together under a single name using structures. The data elements of a structure are known as members.

Definition of Structure

Definition of a structure means creating a template or format that describes the characteristics of its members. A structure can contain any number of member variables in it.

All the variables that would be declared of this structure type, will take the form of this format. The general syntax of a structure definition is -

// structure definition
struct tagname{
               // member variables
               datatype member1;
               datatype member2;
               .................
               .................
               datatype memberN;
              };

Note: It is important to note that definition of a structure format does not reserve any space in memory for the member, space is reserved only when actual variables of this structure type are declared.

Here struct is a keyword, which tells the compiler that a structure is being defined. All the member of the structure should be declare inside curly braces. There should be a semicolon at the end of the curly braces. tagname is the name of the the structure that is used in the program to declare variables of this structure type.

Let us take an example of defining a structure template.

struct student{
               // member variables declaration
               char name[20];
               int roll_no;
               float marks;
              };

Here structure is the structure tag and there are three members of this structure name, roll_no and marks. Structure template can be defined globally or locally. If the template is global then it can be used by all functions while if it is defined locally then only the function containing it can be use it.