8.1 Introduction
A structure is a collection of one or more than one
variable, possibly of different data type, grouped together under a single name
for convenient handling. Thus, a structure might contain integer elements,
floating-point elements and character elements. Structure helps to organize
data especially in large programs, because they provide group of variables of
different data type to be treated as a single unit.
For making, usefulness of structure more clear let us
consider an example. In an organization an employee’s details (i.e. name,
address, designation, salary etc.) have to be maintained. Once possible method
would be to create a multi dimensional array to contain all employee details.
But this is not possible because the variables are of different data type i.e.
name is of type char, salary is of type float and so on. Hence, the simple
solution is the structure. We should be clear about array and structures.
Structure declarations are some what more complicated than
array declarations, since a structure must be defined in terms of its
individual members. In general terms, the composition of a structure may be
defined
struct tag
{
member
1;
member
2;
………...
member
n;
};
Where, struct is a required keyword;
tag is a
name that identifies structure of this type;
and member
1, member 2, ……., member n are individual member declarations.
Note: There is no formal distinction between a
structure definition and a structure declaration; the terms are used
interchangeably.
The individual members can be ordinary variables, pointers,
arrays, or other structures. The member names within a particular structure
must be distinct from one another, though a member name can be the same as the
name of variable that is defined outside of the structure. A storage class,
however can not be assigned to an individual member, and individual members
cannot be initialized within a structure type declaration.
Declaration of a Structure variable
A structure variable is a variable of a structurte type.
Once the structure has been defined, individual structure-type variable can be
declared as follows:
storage-class
struct tag variable 1,variable 2,……………,variable n;
Where, storage-class is an optional storage class specifier,
struct is a
required keyword
tag is the
name of the structure
and
variable 1, variable 2,……, variable n are the structure variables of type tag.
e.g.
struct
account
{
int acc_no;
char acc_type;
char name[80];
float balance;
};
struct
account oldcustomer,newcustomer;
The structure is named account (i.e. the tag is account). It
contains four members: an integer quantity(acc_no), a single
character(acc_type), an 80 element character array(name[80]), and a floating
point quantity(balance).
We can now declare the structure variables oldcustomers and
newcustomers as follows:
struct
account oldcustomer,newcustomer;
It is possible to combine the declaration of structure with
that of structure variables as shown below:
Storage-class
struct tag
{
member 1;
member 2;
…………
memebr n;
}variable1,
variable2, …, variable n;
The tag is optional in this situation.
e.g.
struct
account
{
int acc_no;
char acc_type;
char name[80];
float balance;
}oldcustomer,newcustomer;
OR
struct
{
int acc_no;
char acc_type;
char name[80];
float balance;
}oldcuctomer,newcustomer;
When a structure variable such as newcustomer is declared,
the compiler automatically allocates sufficient memory to accommodate all of
its members.
Example
#include<stdio.h>
#include<conio.h>
struct book
{
char name[20];
float price;
int pages;
};
struct book b1,b2,b3;
main( )
{
printf("\nEnter names,Price,and No of
Pages of 3 books\n");
scanf("%s%f%d",&b1.name,&b1.price,&b1.pages);
scanf("%s%f%d",&b2.name,&b2.price,&b2.pages);
scanf("%s%f%d",&b3.name,&b3.price,&b3.pages);
printf("\nThis is what you
entered");
printf("\n%s\t%f\t%d",b1.name,b1.price,b1.pages);
printf("\n%s\t%f\t%d",b1.name,b1.price,b1.pages);
printf("\n%s\t%f\t%d",b1.name,b1.price,b1.pages);
getch();
}
This program demonstrates two fundamental aspects of
structures:
Declaration
of a structure
Accessing
of a structure elements
Note the following points while declaring a structure
type:
a)The
closing brace in the structure type declaration must be followed by a
semicolon.
b)It
is important to understand that a
structure type declaration does not tell the compiler to reserve any space in
memory. All a structure declaration does is, it defines the form of the
structure.
c)Usually
structure type declaration appears at the top of the source code file, before
any variables or functions are defined. In very large programs they are usually
put in a separate header file, and the file is included (using the preprocessor
directive #include) in whichever
program we want to use this structure type.
Accessing of Structure elements
Structure use a dot(.) operator to access individual
elements. The structure variable name followed by a period and the member name references
that individual member. The general form for accessing a member of a structure
is
structure-name.
member-name
So to refer to pages of the structure defined in our
sample program we have to use.
b1.pages
Similarly, to refer to price we should use,
b1.price
So,to print the name of book we can write
printf("The
book's name is %s",b1.name);
Initializing Structures
Like primary variables and arrays, structure variables can
also be initialized where they are declared. The format used is quite similar
to that used to initialize arrays.
struct book
{
char name[20];
float price;
int pages;
};
struct book
b1={"Basic",130.00,550};
struct book
b2={"Math",150.50,800};
Structure Assignment
The information contained in one structure may be assigned
to another structure of the same type using a single assignment statement. That
is, you do not need to assign the value of each member separately. The
following program illustrates structure assignments:
#include<stdio.h>
#include<conio.h>
struct
{
int a;
int b;
}x,y;
main()
{
x.a=10;
x.b=20;
y=x; //Assign one structure to another
printf("%d",y.a);
printf("%d",y.b);
getch();
}
8.2 Nested structures
Nested structures are structures within structure. Let us
construct two different structures and consolidates it into single nested
structures.
Example 1
struct employee
{
char name[20];
int emp_code;
char designation[20];
float salary;
} emp1, emp2;
struct emp_address
{
int no;
char street[15];
char area[20];
} address1;
These two structures can be consolidated as
struct employee
{
char name[20];
struct emp_address
{
int no;
char street[15];
char area[20];
} address1;
int emp_code;
char designation[20];
float salary;
} emp1, emp2;
Example 2:We can also tag names to define inner
structures
struct date
{
int month;
int day;
int year;
};
struct account
{
int acc_no;
char acc_type;
char name[80];
float balance;
struct date lastpayment;
}customers;
If a structure member is itself a structure, then a member
of the embedded structure can be accessed by writing
variable.member.submember
e.g. customers.lastpayment.month
Example 3:A sample to demonstrate nesting of structure
#include<stdio.h>
#include<conio.h>
struct address
{
char phone[15];
char city[25];
int citycode;
};
struct emp
{
char name[25];
struct address a;
};
void main()
{
int i;
struct emp e={"Jack","54515","KTM",101};
printf("\nname=%s\tPhone=%s",e.name,e.a.phone);
printf("\nCity=%s\tCitycode=%d",e.a.city,e.a.citycode);
getch();
}
Example 4:
#include <stdio.h>
#include<conio.h>
struct add
{
int door_no;
char street[10];
char place[10];
int pin;
};
struct student
{
char name[10];
int roll_no;
struct add address;
};
main()
{
struct student stud;
printf("Enter the name of the student:");
scanf("%s",stud.name);
printf("Enter the roll no. of the student:");
scanf("%d",&stud.roll_no);
printf("Enter the door no.:");
scanf("%d",&stud.address.door_no);
printf("Enter the street name:");
scanf("%s",stud.address.street);
printf("Enter the area name:");
scanf("%s",stud.address.place);
printf("\nThe student's details are....\n");
printf("\nThe name is %s",stud.name);
printf("\nThe roll no is %s",stud.roll_no);
printf("\nThe door no is %d",stud.address.door_no);
printf("\nThe area name is %s",stud.address.place);
printf("\nThe street name is %s",stud.address.street);
getch();
}
It is also permissible to nest more than one type of
structures.
struct
personal_record
{
struct name_part name;
struct address_part address;
struct date_aprt dateofbirth;
…………….
};
struct
personal_record personal;
The first member of this structure is name which is of the
type name_part. Similarly other members have their own structure types.
8.3 Array of structures
Since we can create an array of any valid type, it is
possible to define an array of structure also; i.e. an array in which each
element is a structure. To create the array of structures, you must first
define a structure and then declare an array variable of that type. For
example, to declare a 100-element array of structures of type books, you can
write
struct book
b1[100];
This creates 100 sets of variables that are organized as
defined in the structure book.
To access a specific structure, index the structure name.
For example, to print the price of
structure 3, write
printf("%f",b1[2].price);
Like all array
variables, arrays of structures begin indexing at 0.
Example: To demonstrate arrays of
structures
#include<stdio.h>
#include<conio.h>
struct marks
{
int english;
int math;
int computer;
int total;
};
void main()
{
int i;
static struct marks student[3]={
{50,70,91,0},{75,55,72,0},{54,41,72,0}};
printf("English\tMath\tComputer\tTotal");
for(i=0;i<3;i++)
{
student[i].total=student[i].english+student[i].math+student[i].computer;
printf("\n%d\t\t%d\t\t%d",student[i].english,student[i].math,student[i].computer, student[i].total);
}
getch();
}
Example: Storing book information using
structure
#include<stdio.h>
#include<conio.h>
struct book
{
char name[20];
float price;
int pages;
}b[100];
void main()
{
int i;
for(i=0;i<=99;i++)
{
printf("\n Enter Name, Price, and Pages:");
scanf("%s%f%d",&b[i].name,&b[i].price,&b[i].pages);
}
for(i=0;i<=99;i++)
{
printf("\n%s%f%d",b[i].name,b[i].price,b[i].pages);
}
getch();
}
This provides space in memory for 100 structures of the type
structure book. In an array of structures all elements of the array are stored
in adjacent memory locations. Since each element of this array is a structure,
and since all structure elements are always stored in adjacent locations you
can visualize the arrangement of array of structures in memory.
e.g. b[0]'s name, price, and pages in memory would be
immediately followed by b[1]'s name, price, and pages, and so on.
Note that the array is declared just as it would have been,
with any other array. Since student is an array, we use the usual
array-accessing methods to access individual elements and then the member
operator to access members.
Example
struct employee
{
char name[20];
char roll_no[5];
int salary;
} emp [5];
The above declaration defines five instances of the variable
emp of the type struct employee. They could be initialized in this manner.
struct employee
{
char name[20];
char roll_no[5];
int salary;
} emp [5] = { {"james","e01",
2000},
{"Jerry","e02",
4100},
{"Sheryl","e03", 2500},
{"Vicky","e04", 5000}
};
Actually size need not to be specified, because the
initialization by itself will determine the size. In above initialization part,
every particular employee’s details have been enclosed in braces. This is not
necessary, but it improves the clarity of code. In case a member is not be
initialized, the value for it can be omitted. Assume the name and salary of the
employee is not known; the declaration will be as follows.
{ ,”e06”, }
In case any member of structure can be accessed using the
index number along with the structure name. For e.g., if he/she wants to print
the name of the first employee,
printf (“The name of the first employee is %s”, emp
[0].name);
User-Defined datatype
C language provides the opportunity to define new datatype
equivalent to the existing system using the typedef statement. Let us take an
example. The declaration would be
typedef struct add
{
int dd;
int mm;
int yyyy;
}dob;
dob emp_date_of_birth;
The above declaration variable emp_date_of_birth has now
become the type of structure add.
8.4 Structures and
functions
C supports the passing of structure values as arguments of
functions. There are three methods by which the values of a structure can be
transferred from one function to another.
The first method is to pass each member of the
structure as an actual argument of the function call. The actual arguments are
then treated independently like ordinary variables. This is the most elementary
method and becomes unmanageable and inefficient when the structure size is
large.
The second method involves passing of a copy of the
entire structure to the called function. Since the function is working on a
copy of the structure, any changes to structure members within the function are
not reflected in the original structure(in the calling function). It is,
therefore, necessary for the function to return the entire structure back to
the calling function. All compilers may not support this method of passing the
entire structure as a parameter.
The third method employs a concept called pointer to
pass the structure as an argument. In this case, the address location of the
structure is passed to the called function. The function can access indirectly
the entire structure and work on it. This is similar to the way arrays are
passed to the functions. This method is more efficient as compared to the
second one.
1. Passing Structure Members to Functions
When you pass a member of a structure to a function, you are
actually passing the value of that member to the function.
E.g.
struct fred
{
char x;
int y;
float z;
char s[10];
}mike;
Here are examples of each member being passed to function
e.g.
function(mike.x); //Passes character
value of x
function1(mike.y);
//Passes integer value of y
function2(mike.z);
//Passes float value of z
function3(mike.s)
//Passes address of string s
function4(mike.s[2]);
//Passes character value of s[2]
If you wish to pass the address of an individual structure
member, put the & operator before the structure name
e.g.
function(&mike.x); //Passes address
of character x
function1(&mike.y);
//Passes address of integer y
function2(&mike.z); //Passes address
of float z
function3(mike.s)
//Passes address of string s
function4(&mike.s[2]);
//Passes address of character s[2]
Remember that the & operator preceds the structure name,
but not the individual member name.
2. Passing Entire Structures to Functions
When a structure is used as an argument to a function, the
entire structure is passed using the standard call-by-value method. This means
that any changes made to the contents of the structure inside the function to
which it is passed do not affect the structure used as an argument.
When using a structure as a parameter, remember that the
type of the argument must match the type
of the parameter. For example, in the following program both the argument arg
and the parameter parm are declared as the same type of structure.
Example 1:
#include<stdio.h>
#include<conio.h>
struct test
{
int a,b;
char ch;
};
void function(struct test parm);
main( )
{
struct test arg;
arg.a=1000;
function(arg);
getch();
}
void function(struct test parm)
{
printf("%d",parm.a);
}
Example 2:
#include<stdio.h>
#include<conio.h>
typedef struct
{
char name[20];
int price;
int quantity;
}stores;
stores update(stores product,int p,int q)
{
product.price+=p;
product.quantity+=q;
return(product);
}
float mul(stores stock)
{
return(stock.price*stock.quantity);
}
void main( )
{
float value;
int p_increment,q_increment;
static stores item={"XYZ",25,12};
printf("\nInput increment values:");
printf("price increment and quantity
increment\n");
scanf("%d%d",&p_increment,&q_increment);
item=update(item,p_increment,q_increment);
printf("Update values of item\n\n");
printf("Name %s\n",item.name);
printf("Price %d\n",item.price);
printf("Quantity %d\n",item.quantity);
value=mul(item);
printf("\n Value of the item=%f\n",value);
getch();
}
8.5 Structure and Pointer
( Refer next chapter )
8.6 Unions
Unions have the same relationship to structures. Both
structures and unions are used to group a number of variables of different data
type together. But the difference is that the structure enables us to reserve a
separate place in memory for every individual member of the structure. Whereas
with union, it enables to reserve the definite place in memory and use it for
all members of the unions. This implies that, although a union may
contain many members of different types, it can handle only one member at a
time.
In unions while deciding the size of the memory to reserved,
it will reserve the memory space equals to size occupied by the union member
with data type that has highest precision. i.e. if there is union with two data
members of type int, float. Here, since float has higher precision, union will
occupy the memory space of byte.
Like structures, a union can be declared using the keyword
union as follows:
union item
{
int m;
char c;
float x;
}code;
Example:
#include<stdio.h>
#include<conio.h>
union course
{
int major;
char minor[10];
};
struct student
{
char name[20];
int rollno;
union course course_no;
}student1;
main()
{
char c_name;
clrscr();
printf("Enter the name of the student:");
scanf("%s",student1.name);
fflush(stdin);
printf("Enter the roll no of the student:");
scanf("%d",student1.rollno);
fflush(stdin);
printf("Enter the course('M' for major or 'm' for minor)");
scanf("%c",&c_name);
fflush(stdin);
if(c_name=='M')
{
printf("The course('1'or '2')?");
scanf("%d",&student1.course_no.major);
fflush(stdin);
}
if(c_name=='m')
{
printf("Enter the name of
the course:");
scanf("%d",&student1.course_no.minor);
fflush(stdin);
}
printf("\nPress any key to exit...");
getch();
}
How is the structure different from an array?
Ø
An array can hold multiple elements of same data
type whereas a structure can hold multiple elements of different data types
Ø
The component element of an array is referenced
by the array name and the index value e.g. name[3], a[5] etc where as component element of a
structure is referenced by the structure name and the element name e.g.
book.id, stu.name etc.
Differentiate between Structure and Union
structure
|
union
|
||
1.
|
Members
of a structure doesn't share space
|
1.
|
Members
of a union share space
|
2.
|
Don’t'
Conserves storage
|
2.
|
Conserves
storage
|
3.
|
Each and
every data member defined can be accessed whenever it has been defined.
|
3.
|
Only the
last data member defined can be accessed
|
4.
|
Each data
member will occupy its own size finally the size of the strcture in the sum
of the total memory occupied by each member.
|
4.
|
The size
required by a union variable is the size required by the member requiring the
largest size
|
5.
|
Specially
designed to create own data type or typically used to create simple database.
|
5.
|
Specially
designed to handle or control the hardware operation.
|
6
|
Example:
struct book{int id;
char name[10];
}b;
|
Example:
union selection{
char major[10];
char minor[15];
}u;
|
End of Chapter Eight
[ Note: If you have any problems regarding this then you can post the
problem in comment box. we will try to solve this here. Or if you know
any solution, you can also help :) ]
No comments:
Post a Comment