Structures

Structure in C

We know that variables can hold a piece of information and arrays can hold a number of pieces of information of same type/ these tow data types can handle a great variety of situations. Often, we need to deal with entities that are collection of dissimilar data types. For example, to store data about a book, we might want to store its name (a string), its price (a float) and number of pages in it (an int). If data about three such books are to be stored, then we can follow two approaches:

a) Construct individual arrays, ne for storing names, another for storing prices and still another for storing number of pages.
b) Use a structure variable.

  • A better way of organizing the data is to create a new user-defined data type that contains all the pieces of data organized into one structure
  • C provides a data structure called a struct that allows you to create new data types
  • Keyword ‘struct’ is used to declare structure.
  • The new data type is an organized aggregate of other data types
  • A struct has a name (e.g., structureName)
  • The variables which are declared inside the structure are called as ‘members of structure’.
  • A struct has members or fields, which can be any data types, such as char, int, float, string, array, bit field, and other struct

Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
– – – – – – – – – – –
– – – – – – – – – – –
<data-type> element n;
}struct_var;

Structure in c language

Note:
1. Structure is always terminated with semicolon (;).
2. Structure name as emp_info can be later used to declare structure variables of its type in a program.

Things to remember:

  • Declaration of Structure reserves no space.
  • It is nothing but the “Template / Map / Shape” of the structure.
  • Memory is created, very first time when the variable is created / Instance is created.

Syntax to create a variable for a structure: struct structure_name , ……..

Ways of Declaring Structure Variable / Structure Instance:
Way 1 : Immediately after Structure Template
struct date
{
int date;
char month[20];
int year;
} today; // ‘today’ is name of Structure variable


Way 2 : Declare Variables using struct Keyword
struct date
{
int date;
char month[20];
int year;
};
struct date today;
/*———————————–
date : Name of Structure
today : Structure Variable
———————————- */
Accessing structure members: A structure contains many elements. Each elements of a structure can
be referred to / accessed by using the component selection operator “.” (Dot).
Syntax:
structure_var.member;

#include <stdio.h>
#include <conio.h>
struct comp_info
{
char nm[100];
char addr[100];
}info;
void main()
{
clrscr();
printf(“\n Enter Company Name : “);
gets(info.nm);
printf(“\n Enter Address : “);
gets(info.addr);
printf(“\n\n Company Name : %s”,info.nm);
printf(“\n\n Address : %s”,info.addr);
getch();
}

Memory map of structure elements: The structure elements are always stored in the contiguous
locations.

Memory map of structure elements

Array in Structures: We can also include arrays as structure elements, but accessing of such kind of elements is bit complex as shown below.
#include <stdio.h>
struct result{
int rno;
int mrks[5];
char name[20];
}res;
void main(){
int i,total;
total = 0;
printf(“\nEnter Name and Roll Number : “);
scanf(“%s%d”,res.name,&res.rno);
printf(“\nEnter Marks of 3 Subjects : “);
for(i=0;i<3;i++){
scanf(“%d”,&res.mrks[i]);
total = total + res.mrks[i];
}
printf(“\nname=%s\nRoll Number : %d”,res.name,res.rno);
printf(“\nMarks are :”);
for(i=0;i<3;i++){
printf(” \t%d”,res.mrks[i]);
}
printf(“\n\n\t Total is : %d”,total);
}
Array of structures: To store more than one record of a structure under same name, we can also creates an array variable to the corresponding structure. The storage of elements in array of structures would be as follows.

Array of structures

#include < stdio.h >
#include < conio.h >
struct emp
{
int empno;
char name[10];
int sal;
}e1[5];
void main()
{
int i;
clrscr();
for(i=0;i < 5;i++)
{
printf(“Enter the empno\n”);
scanf(“%d”,&e1[i].empno);
printf(“Enter the name\n”);
flushall();
gets(e1[i].name);
printf(“Enter the salary\n”);
scanf(“%d”,&e1[i].sal);
}
printf(“The record is\n”);
for(i=0;i < 5;i++)
{
printf(“\n %4d”,e1[i].empno);
printf(“%8s”,e1[i].name);
printf(” %4d\n”,e1[i].sal);
}
getch();
}


Copying of structure elements:

The values of a structure variable can be assigned to another structure variable of the same type using the assignment operator. The elements of the structure can be copied piece-meal or all at once. This is illustrated in the following example:
#include <stdio.h>
struct emp
{
int eno;
char ename[50];
float esal;
};
int main()
{
int i;
struct emp e1={1001,”naresh”,50000};
struct emp e2,e3;
e2.eno=e1.eno;
strcpy(e2.ename,e1.ename);
e2.esal=e1.esal;
e3=e2;
printf(“\n%d\t%s\t%f\n”,e1.eno,e1.ename,e1.esal);
printf(“\n%d\t%s\t%f\n”,e2.eno,e2.ename,e2.esal);
printf(“\n%d\t%s\t%f\n”,e3.eno,e3.ename,e3.esal);
return 0;
}

Unions

Unions were used back in the days when computer memory was at a premium. A union basically allows a variable to have more than one type; but only one of these types can be used. However the members that we compose a union all share the same storage area within the computer’s memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to conserve memory. They are useful for the application involving multiple members where values need not be assigned to all the members at any one time. Unions like structure contain members whose individual data types may differ from one another also. Like structures union can be declared using the keyword union as follows:
Syntax:
union [tag] { member-list } [declarators];

Tag: The type name given to the union.
Member-list: List of the types of data the union can contain. See Remarks.
Declarators: Declarator list specifying the names of the union.
Struct emp
{
Int eno;
Char ename[20];
Float esal;
} e;

Here is an example:
union tag
{
char name[26];
int age;
float height;
} player;
player.name=’Bhavani Shankar Kandregula’;
player.age=27;
player.weight=61;

 

Difference between structure and union

STRUCTURE
  • The keyword struct is used to define a structure.
  • The size of the structure is equal to the sum of the sizes of its members.
  • Each member within a structure is assigned a unique storage area.
  • Individual members can be accessed at a time.
  • Altering the value of a member will not affect other members of the structure.
UNION
  • The keyword union is used to define a union.
  • The size of the union is equal to the size of the largest member.
  • Memory allocated is shared by individual members of the union.
  • Only one member can be accessed at a time.
  • Altering the value of any of the member will alter other member values.

Program to find the structure using sizeof () operator:
union myunion
{
int i;
double d;
char c;
}mu;
int main()
{
printf(“%d\n”,sizeof(union myunion));
printf(“%d\n”,sizeof(mu));
printf(“%d\n”,sizeof(mu.i));
printf(“%d\n”,sizeof(mu.d));
printf(“%d\n”,sizeof(mu.c));
return 0;
}

Memory allocation for union elements:
  • Union is user defined data type used to stored data under unique variable name at single memory location.
  • Union is similar to that of structure..
  • But the major difference between structure and union is ‘storage.’ In structures, each member has its own storage location, whereas all the members of union use the same location.
  • Union contains many members of different types; it can handle only one member at a time.

#include
int main()
{
union a
{
int i;
char ch[2];
};
union a u;
u.ch[0]=3;
u.ch[1]=2;
printf(“%d, %d, %d\n”, u.ch[0], u.ch[1], u.i);
return 0;
}

Explanation: The system will allocate 2 bytes for the union. The statements u.ch[0]=3; u.ch[1]=2; store data in memory as given below.

Union in c

Scroll to top