C Structures

Arrays provide the facility for grouping related data items of the same type into a single object. However, sometimes we need to group related data items of different types. An example is the inventory record of a stock item that groups together its item number, price, quantity in stock, reorder level etc. In order to handle such situations, C provides a data type, called structures, that allows a fixed number of data items, possibly of different types to be treated as a single object. It is used to group all related information into one variable.

Definition

A structure is a heterogeneous collection of related fields. Here fields are called structure member or structure element. Every field has a different type-specifier (data-type).

The definition of structure of opposite of array, because array is set of homogeneous elements. But the structure has a deep relationship with array.

Structure Variables

The general syntax used to declare a structure and structure variables is written as below:

struct structure-tag
{
  date-type1 strcture element-1 or member-1;
  date-type2 strcture element-2 or member-2;
  date-type3 strcture element-3 or member-3;
  ......................................................;
  date-type n strcture element-n or member-n;
};
main()
{
  struct structure-tag v1,v2,..........vn;
  local declaration;
  executable statements;
}

Simple Structure Program:

#include <stdio.h>
#include <conio.h>
struct str
{
  char name[10],city[20];
};
void main()
{
  struct str obj1={"Jack","Jermany"};
  clrscr();

  printf("Name=%s",obj1.name);
  printf("\n City=%s",obj1.city);
  getch();
}

Output is as follows:

Name=Jack
City=Jermany
Note: struct is the keyword which we can’t use as a variable.

Structure within Structure (Nested Structure)

Example Program:

#include <stdio.h>
#include <conio.h>

struct str1      //First Structure
{
  char name[10];
  struct str2   //Second Structure
  {
    city[20];
  }objstr1;
}objstr2;

void main()
{
  printf("Enter the Name and City\n");
  scanf("%s%s",objstr1.Name,objstr2.city);
  printf("\nName=%s",objstr1.name);
  printf("\n City=%s",objstr1.objstr2.city);
  getch();
}

Output is as follows:

Enter the Name and City
James
New York
Name=James
City=New York

Structure and array

Arrays play a very important role in structure. Structure has two types of view with the array. The two types of relationship of structure with array.

Example Program:

/*Program to illustrate the concept of use of an Array within the Structure*/
#include <stdio.h>
#include <conio.h>
struct str
{
  name[10],char city[10];
};

void main()
{
  struct str n[10];
  int i=1;
  clrscr();
  printf("Enter the Ten Emp...\n");

  for(i=1;i
Related Post