0% found this document useful (0 votes)
76 views31 pages

Understanding C Structures and Unions

The document explains the concept of structures in C programming, which allows grouping of different data types under a single name for convenient handling. It covers the definition, declaration, initialization, and accessing of structure members, as well as features like nesting and copying structures. Additionally, it provides examples and syntax for creating and managing structures, including operations on individual members.

Uploaded by

badimela1508
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views31 pages

Understanding C Structures and Unions

The document explains the concept of structures in C programming, which allows grouping of different data types under a single name for convenient handling. It covers the definition, declaration, initialization, and accessing of structure members, as well as features like nesting and copying structures. Additionally, it provides examples and syntax for creating and managing structures, including operations on individual members.

Uploaded by

badimela1508
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-II

STRUCTURES AND UNIONS

As we have seen earlier, Arrays can be used to represent a group of data items that
belong to the same data type, such as int (or) float. However we cannot use an array if we want
to represent a collection of data items of different types using a single name. Fortunately, c
supports a constructed data type known as structures which is a mechanism for packing of data
belong to different data types. A structure is a convenient tool for handling a group of logically
related data items. For example is an employee record that consists of the name, date of birth,
address, salary, ID number etc. of the person involved. A structure allows the programmer to
group all these properties into one unit. Structures help to organize complex data in a more
meaningful way.
Examples:
 time : seconds,minutes,hours
 date : day,month,year
 book : author,title,price,year
 address: name,doornumber,street,city
 customer : name,telephone,city,catagory
Features of Structures:
 To copy elements of one array to another array of same data type elements are copied one by
one. It is not possible to copy elements at a time. Where as in structure it is possible to copy
the contents of all structure elements of different data types to another structure variable of its
type using assignment (=) operator. It is possible because structure elements are stored in
successive memory locations.
 Nesting of structures is possible i.e. one can create structure within the structure. Using this
feature one can handle complex data types.
 It is possible to pass structure elements to a function. This is similar to passing an ordinary
variable to a function. One can pass individual structure elements (or) entire structure by
value (or) address.
 It is also possible to create structure pointers. We can also create a pointer pointing to structure
elements. For this we require “->‟ operator.

Define a structure:
Definition: A structure is a collection of one or more variables grouped together under a single name
for convenient handling. Here the variables that are grouped together can have different types.
(or)
A structure is a collection of heterogeneous data elements.
(or)
C Structure is a collection of different data types which are grouped together and each element in a C
structure is called member.
If you want to access structure members in C, structure variable should be declared.
Many structure variables can be declared for same structure and memory will be allocated for each
separately.
It is a best practice to initialize a structure to null while declaring, if we don’t assign any values to
structure members.
Defining a structure: structure must be defined first their format and that may be used later to
declare structure variables. Structure is defined using a keyword struct followed by the name of the
structure (optional) followed by the body of the structure. The members of the structure are declared
within the structure body. The general format of defining a structure is
Syntax: struct struct-name
{
data_type var-name1;
data_type var-name2;
.
.
data_type var-nameN;
};
Example: struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structure to hold the details of structure members(or)structure elements
.Each member may belong to a different type .structure name is the identifier which represents the
name of the structure and is also called as structure tag. The tag name may be used subsequently to
declare variables that have the tags structure. The structure body contains structure
members(or)structure elements .For example
Example: struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
Declaring structure variables: After defining a structure format we can declare variables of that
type. we can declare structure variables using the structure-tag anywhere in the program. A structure
variable declaration is similar to the declaration of variables of any other data types. It includes the
following elements.
 The keyword struct
 The structure tag name
 List of variable names separated by commas
 A terminating semicolon
Syntax: struct structure_tag structure_var1, structure _var2,.......structure _varN;
Example: struct book_bank book1,book2,book3;
Each one of the variables has four members as specified by the template.
The complete declaration may look like this
Declaring Structure variables separately:
syntax: struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};struct book_bank book1,book2,book3;
Remember that the members of a structure themselves are not variables. They do not occupy any
memory until they are associated with the structure variables.
Declaring Structure Variables with Structure definition (or) Tagged structure:
Tagged structure: It is also allowed to combine both the template declaration and variable
declaration in one statement.

Syntax: struct book_bank


{
char title[20];
char author[15];
int pages;
float price;
} book1,book2,book3;
variable structure: The use of tag name is optional
syntax: struct
{
char title[20];
char author[15];
int pages;
float price;
} book1,book2,book3;
The above declares book1,book2, book3 as structure variables representing three books, but does not
include a tag name. However, this approach is not recommended for two reasons.
 Without a tag name, we cannot use it for future declarations
 Normally, structure definitions appear at the time of beginning of the program file, before any
variables (or) functions are defined. They may also appear before the main, along with macro
definitions, such as #define. In such cases, the definition is global and can be used by other
functions as well.
Accessing the Members of a structure: we can access and assign values to the members of
structure in a number of ways. As we mentioned earlier, the members of the structure themselves are
not the variables. They should be linked to the structure variable in order to make them meaningful
members. The link between a member and a variable is established using the member operator '.'
which is also known as 'dot operator'(or) period operator.
For example, [Link] is the variable representing the price of book1.
Here we can see how we would assign values to the members of book1
strcpy([Link],”basic”);
strcpy([Link],”balagurusamy”);
[Link]=240;
[Link]=120.36;
We can also use scanf to give the values through the keyboard
scanf(“%s”,[Link]);
scanf(“%d”,&[Link]);
Example: Define a structure type, struct personal that would contain person name, date of joining
and salary, using this structure, write a c program to read this information for one person from the
keyboard and print the same on the screen.
#include<stdio.h>
struct personal
{
char name[20];
int day;
char month[10];
int year;
float salary;
};
void main()
{
struct personal person;
printf(“enter name,day , month,year,salary”); scanf(“%s%d%s%d
%f”,[Link],&[Link], [Link],
&[Link],&[Link]); printf(“%s%d%d%d
%f”,[Link],[Link],[Link],[Link],
[Link]);
getch();
}
Example #include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
} record;
Void main()
{
[Link]=1;
strcpy([Link], "Raju");
[Link] = 86.5;
printf(" Id is: %d \n", [Link]);
printf(" Name is: %s \n", [Link]);
printf(" Percentage is: %f \n", [Link]);
getch();
}
Example: #include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( [Link], "C Programming");
strcpy( [Link], "Nuha Ali");
strcpy( [Link], "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( [Link], "Telecom Billing");
strcpy( [Link], "Zara Ali");
strcpy( [Link], "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", [Link]);
printf( "Book 1 author : %s\n", [Link]);
printf( "Book 1 subject : %s\n", [Link]);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", [Link]);
printf( "Book 2 author : %s\n", [Link]);
printf( "Book 2 subject : %s\n", [Link]);
printf( "Book 2 book_id : %d\n", Book2.book_id);
}
Output: Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Structure Initialization: Like other variables, a structure variable also can be initialized at compile
time.
Syntax: main()
{
struct
{
int age;
float height;
} student={50,150.96};
-------------------------------
-------------------------------
}
The above syntax assigns the value 50 to [Link] and 150.96to [Link]. There is one to
one correspondence between the members and their initializing values.
Suppose you want to initialize more than one structure variable
syntax: main()
{
struct st_record
{
int age;
float height;
};
struct st_record student1={50,150.96};
struct st_record student2={30,120.16};
-------------------------------
-------------------------------
}
we have another method to initialize a structure variable outside of the function.\
syntax: struct st_record
{
int age;
float height;
}student1={50,150.96};
main()
{
struct st_record student2={30,120.16};
-------------------------------
-------------------------------
}
Note that compile time initialization of a structure variable must have the following elements.
 The keyword struct
 The structure tag name
 The name of the variable to be declared
 The assignment operator '='
 A set of values for the members of the structure variable, separated by commas and enclosed
in braces.
 A terminating semicolon.
Rules for initializing structures:
 We cannot initialize individual members inside the structure template.
 The order of values enclosed in braces must match the order of members in the structure
definition.
 It is permitted to have partial initialization. we can initialize only the first few members and
leave the remaining blank. The uninitialized members should be only at the end of the list.
 The uninitialized members will be assigned default values as follows.
 zero for integer and floating point numbers.
 '\0' for character strings.
Example: write program for demonstrating structure member initialization
#include<stdio.h>
void main()
{
struct student /*Declaraing the student structure*/
{
int marks1,marks2,marks3;
};
struct student std1={55,66,80}:/*initializing ,marks for student 1*/
struct student std2={60,85,78}:/initializing marks for student 2*/
clrscr();
/*Displaying marks for student 1*/
printf(“marks obtained by 1st student: %d and
%d”,std1.marks1,std1.marks2.std1.marks3);
/*Displaying marks for student 2*/
printf(*\nMarks obtained by 2nd student:
%d.%d”,std2.marks1.std2.marks2.std2.marks3);
getch();
}
Copying & Comparing Structure Variables: Two variables of the same structure type can be
copied the same way as ordinary variables. If person1 and person2 belongs to the same structure,
then the fallowing assignment operations are valid:
person1 = person2; assigns person1 to person2
person2 = person1; assigns person2 to person1
However, the statements such as,
person1 = = person2
person1! = person 2 are not permitted.
C does not permit any logical operations on structure variables. In such cases, we need to compare
them by comparing the members individually.
Example: program to illustrate the comparison & copying of structure variables
#include<stdio.h>
struct class
{
int no;
char name[20];
float per;
};
main()
{
int x;
struct class stu1={111,”Ramu”,72.50};
struct class stu2={222,”Reddy”,67.00};
struct class stu3;
stu3=stu2;
x=([Link]==[Link]&&[Link]==[Link])?1:0;
if(x==1)
printf(“\n student2 and sc tudent3 are same\n”);
else
printf(“\n student2 and student3 are different\n”);
}
Operations on Individual Members of the Structure: As pointed earlier, the individual members
are identified using the member operator (.). A member with the dot operator along with its structure
variable can be treated like any other variable name and therefore it can be manipulated using
expressions and operators. Consider the previous example program; we can perform the following
operations.
if( [Link] = = 111)
[Link] +=10.00;
float sum =stu1. per + [Link];
[Link] *= 0.5;
We can also apply the increment and decrement operators to numeric type members. For example, the
following statements are valid:
[Link]++;
++ [Link];
Example: C Program to Store Information (name, roll and marks) of a Student Using Structure
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
};
main()
{
struct student s;
printf("Enter information of students:\n\n");
printf("Enter name: ");
scanf("%s",[Link]);
printf("Enter roll number: ");
scanf("%d",&[Link]);
printf("Enter marks: ");
scanf("%f",&[Link]); printf("\
nDisplaying Information\n");
printf("Name: %s\n",[Link]);
printf("Roll: %d\n",[Link]);
printf("Marks: %.2f\n",[Link]);
}
Output: Enter information of students:
Enter name: Adele
Enter roll number: 21
Enter marks: 334.5
Displaying
Information name:
Adele
Roll: 21
Marks: 334.50
Structures within Structures [Nested Structures]: A structure within a structure means nesting of
structures. Nesting of structures is permitted in C. Let us consider the fallowing structure defined to
store information about the salary of employees.
struct salary
{
char name[20];
char dept[20];
int basic_pay;
int dearness_allowance;
int house_rent_allowance;
int city_allowance;
} employee;
This structure defines name, department, basic pay and three kinds of allowances. We can group all
the items related to allowances together and declare them under a substructure as shown below:
struct salary
{
char name[20];
char dept[20];
struct
{
int dearness;
int house_rent;
int city;
} allowance;
} employee;
The “salary‟ structure contains a member named „allowance‟, which itself is a structure with three
members. The members contained in the inner structure namely, dearness, house_rent, and city.
These members can be referred to as:
[Link];
[Link].house_rent;
[Link];
An inner-most member in a nested-structure can be accessed by chaining all the concerned structure
variables (from outer-most to inner-most) with the member using the dot operator. The fallowing
statements are invalid:
[Link]--------------actual member is missing
employee.house_rent--------------inner structure variable is missing
We can also use tag names to define inner structures. For example,
struct pay
{
int da;
int hra;
};
struct salary
{
char name[10];
struct pay allowance;
struct pay arrears;
};
struct salary employee [100];
Here, pay template is defined outside the salary template and is used to define the structure of
allowance and arrears inside the salary structure. C permits nesting up to 15 levels
The pay structure members can be referred to as:
[Link];
[Link];
[Link];
[Link];
Example: #include <stdio.h>
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
int main()
{
printf("\nEmployee Name : %s",[Link]);
printf("\nEmployee SSN : %d",[Link]);
printf("\nEmployee Salary : %f",[Link]);
printf("\nEmployee DOJ : %d/%d/%d",
[Link],[Link],[Link]);
}
Output : Employee Name : Pritesh
Employee SSN : 1000
Employee Salary : 1000.500000
Employee DOJ : 22/6/1990
Example: implement following student information fields using nested structures
#include<stdio.h>
#include<conio.h
> void main()
{
struct student;
{
int roll_no;
struct name
{
char First[20];
char Middle[20];
char Last[20];
}st_name;
struct dob
{
int day ,month,year;
}std_dob;
struct course
{
char elective 1[20];
char elective2[20];
}st_course;
};
struct student std1;
clrscr();
std.roll_no=34;
strcpy(sdt1.st_name.First,”Krishna”);
strcpy(sdt1.st_name.Middle,”sai”);
strcpy(sdt1.st_name.Last,”reddy”);
std1.st_dob.day=21;
std1.st_dob.month=12;
std1.st_dob.year=1993;
strcpy(std1.st_course.elective1,”Mechanics”);
strcpy(std1.st_course.elective2,”Animation”);
Printf(“\nRoll No.:%d”,[Link] _No);
Printf(“\n Name: %s%s%s”,
std1.st_name.First,std1.st_name.Middle,std1.st_name.Last);
Printf(“\n Date of birth(DD MM YYYY):%d%d%d”,
std1.st_dob.day,std1.st_dob.Month,std1.st_dob.Year);
Printf(“\ncourse electives:%s&%s”,
std1.st_course.elective1,std1.st_course.elcetive2);
getch();
}
Example: Implement the following employee information fields using nested structures
#include<stdio.h>
#include<conio.h>
void main()
{
struct employee
{
int emp_id;
struct name
{
char First[20];
char Mibble[20];
char Last[20];
}emp_name;
char doj[20];
struct G_sal
{
float basic,HRA;
float spl_allow;
}emp_sal;
};
struct employee emp1l
clrscr();
emp1.emp_id=37;
strcpy(emp1.emp_name.first,”M”);
strcpy(emp1.emp_name.middle,”Mahesh”);
strcpy(emp1.emp_name.last,”reddy”);
strcpy([Link],”22/10/2004”);
emp1.emp_sal.basic=17432.00;
emp1.emp_sal.HRA=10032.00;
emp1.emp_sal.spl_allow=5000.00;
Printf(“\n emp id:%d”, emp1.emp_id);
Printf(“\n name:%s%s%s”,emp1.emp_name.First ,emp1.emp_name.Middle
,emp1.emp_name.Last);
Printf(“\n date of joining (DD MM YYYY): %s”,[Link]);
Printf(“\n Gross salary:%.2f”,
emp1.emp_sal.basic+emp1.emp_sal.HRA+emp1.emp_sal.spl_allow);
getch();
}
Arrays of Structures: As you know, C Structure is collection of different data types ( variables )
which are grouped together. Whereas, array of structures is nothing but collection of structures.
Arrays of structures represent each element of an array must be structure type. For example, in
analyzing the marks obtained by a class of students, we may use a template to describe student name
and marks obtained in various subjects and then declare all the students as structure variables. In
such cases, we may declare an array of structures, each element of the array representing a structure
variable.
Syntax: struct structurename
{
datatype var1;
datatype var2;
.
.
datatype varN;
}structurevariable[size];
(or)
struct structurename structurevariable[size];
Example: struct class student [100];
The above defines an array called „student‟ that consists of 100 elements. Each element is defined
to be of the type struct class.
Consider the following declaration:
struct marks
{
int eng;
int tel;
int sci;
};
main( )
{
struct marks student[3]={45,76,87},{78,68,79},{34,23,14};
................
................
}
This declares the student as an array of three elements student [0], student [1],student [2] and
initializes the members as follows:
student[0].eng=45;
student[0].tel=76;
.......................
.......................
student[2].sci=14;
Example: write a program to calculate the subject-wise and student-wise totals and store as a
part of the structure
#include<stdio.h>
struct marks
{
int eng;
int tel;
int sci;
int tot;
};
main( )
{
int i;
struct marks student[3]={{45,67,81,0},{75,53,69,0},{57,36,71,0}};
struct marks t={0,0,0,0};
clrscr();
for(i=0;i<3;i++)
{
student[i].tot=student[i].eng+student[i].tel+student[i].sci;
[Link]=[Link]+student[i].eng;
[Link]=[Link]+student[i].tel;
[Link]=[Link]+student[i].sci;
[Link]=[Link]+student[i].tot;
}
printf(" STUDENT TOTAL \n\n");
for(i=0;i<3;i++)
printf("stu[%d] : %d\n",i+1,student[i].tot);
printf("SUBJECT TOTAL\n\n");
printf("English:%d\nTelugu:%d\nScience :%d\n",[Link],[Link],[Link]);
printf("\n Grand total : %d\n",[Link]);
getch( );
}
Example2: Write a program to enter 5 dates. Store this information in array of structures
#include<stdio.h>
struct date
{
int day, year;
char month[10];
} b_days [5];
main( )
{
int i;
for(i=0;i<5;i++)
{
printf(“\nEnter 5 dates:”);
scanf(“%d %d %s”,&b_days[i].day, &b_days[i].year, b-
days[i].month);
}
for(i=0;i<5;i++)
{
printf(“\nbirth day dates are %d %d %s”, b_days[i].day,
b_days[i].year,b_days[i].month);
}
}
Arrays within Structures: C permits the use of array as structure members. We have already used
arrays of characters inside the structure. Similarly, we can use single or multi-dimensional arrays of
type either int or float.
Example:
struct marks
{
int no;
int sub[5];
float fee;
} stu [10];
Here, the member „sub‟ containing 5 elements. These elements can be accessed using appropriate
subscripts. For example,
stu[1].sub[2];
would refer to the marks of third subject by the second student.
Example: Rewrite the program of above example 1 using an array member to represent the
three subjects.
#include<stdio.h>
main( )
{
struct marks
{
int sub[3];
int total;
};
struct marks student[3]= {10,20,30,0,10,20,30,0,10,20,30,0};
struct marks t={0,0,0,0};
int i,j,k=0;
clrscr();
for(i=0;i<=2;i++,k++) /* „i? represent student*/
{
for(j=0;j<=2;j++) /* „j? represent subjects */
{
student[i].total+=student[i].sub[j];
[Link][i]+=student[i].sub[i];
}

t. total+= student[i].total;
}

printf("\nSTUDENT TOTAL\n\n");
for(i=0;i<=2;i++)
printf("student[%d] %d\n", i+1,student[i].total);
printf("\nSUBJECT TOTAL\n\n"); for(k=0;k<=2;k+
+)
printf("subject-%d\t %d\n",k+1,[Link][k]);
printf("\nGrand Total = %d\n", [Link]);
getch();
}
Structures and Functions: C supports the passing of structure values as arguments to a function.
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 read independently like ordinary variables. This is the
most elementary approach 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
[Like, call by value]. Since the function is working on a copy of the structure, any changes to
the structure members within the function are not reflected in the original structure.
Therefore, it is necessary for the function to return the entire structure back to the calling
function.
Note: All the compilers may not support this method of passing the entire structure as a
parameter.
 The third approach employs a concept called pointers 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 functions. This method is more efficient as compared to the second one.
Passing individual structure member as an argument to a function: Here we can pass individual
structure members as an argument to a function.
Example: Write a c program to simulate the multiplication of two fractions by passing
individual structure members to a function
#include<stdio.h>
struct fraction
{
int num;
int denom;
};
struct fraction multiply(int,int,int,int);
main()
{
struct fraction f1,f2,result;
clrscr();
printf("\nEnter numerator and denominator of first fraction:");
scanf("%d%d",&[Link],&[Link]);
printf("\nEnter numerator and denominator of second fraction:");
scanf("%d%d",&[Link],&[Link]);
result=multiply([Link],[Link],[Link],[Link]); printf("\
nThe result after multiplication of two fractions is:"); printf("\n
%d / %d",[Link],[Link]);
}
struct fraction multiply(int a,int b,int x,int y)
{
struct fraction r;
[Link]=a*x;
[Link]=b*y;
return r;
}
Passing structure by value (call by value):A structure variable can be passed as an argument as
normal variable to the called function. If structure is passed by value, change made in structure
variable in the called function does not reflect in original structure variable in the calling function.
General format of sending a copy of a structure to the called function:
function name (structure_variable_name);
The called function takes the fallowing form:
data type function name (struct_type structvariablename)
{
-----------
-----------
return (expression);
}
Important points to remember:
 The called function must be declared for its type, appropriate to the data type it is expected to
return. For example, if it is returning a copy of the entire structure, then it must be declared as
struct with an appropriate tag name.
 The structure variable used as the actual argument and the corresponding formal argument in
the called function must be of the same struct type.
 The return statement is necessary only when the function is returning some data. The
expression may be any simple variable or structure variable or an expression using simple
variables.
 When a function returns a structure variable, it must be assigned to a structure variable of
identical type in the calling function.
 The called function must be declared in the calling function, if it is placed after the calling
function.
Example: write a c program which illustrates sending a structure variable through call by value.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct sbook
{
int pages;
float price;
char title[20],author[30],publisher[30];
};
void dispalybook(struct sbook book1)
{
[Link]+=10.00;
[Link]+=20;
}
main()
{
struct sbook sb={“c language”,”raja”,100.65,25,”technical”);
clrscr();
printf(“\n The book details before the functioncall is”);
printf(“Titles:%s”,[Link]); printf(“Author:
%s”,[Link]); printf(“Price:%f”,[Link]);
printf(“pages:%d”,[Link]); printf(“Publisher:
%s”,[Link]); displaybook(sb);
printf(“\n The book details after the function call”);
printf(“Titles:%s”,[Link]); printf(“Author:
%s”,[Link]); printf(“Price:%f”,[Link]);
printf(“pages:%d”,[Link]); printf(“Publisher:
%s”,[Link]);
getch();

}
Example: Write a C program to create a structure student, containing name and roll. Ask user
the name and roll of a student in main function. Pass this structure to a function and display
the information in that function.
#include <stdio.h>
struct student
{
char name[50];
int roll;
};
void Display(struct student stu);
main()
{
struct student s1;
printf("Enter student's name: ");
scanf("%s",[Link]);
printf("Enter roll number:");
scanf("%d",&[Link]);
Display(s1); // passing structure variable s1 as argument
}
void Display(struct student stu)
{
printf("Output\nName: %s",[Link]);
printf("\nRoll: %d",[Link]);
}

Example: Write a simple program to illustrate the method of sending an entire structure as a
parameter to a function(Passing a copy of the entire structure as an argument to a function).
#include<stdio.h>
#include<conio.h
> struct stores
{
char name[20];
float price;
int qty;
};
main( )
{
struct stores update(struct stores,float,int);
float mul(struct stores);
float p_inc,val;
int q_inc;
struct stores item={"pen",5.50,10};
clrscr();
printf("\nInput increment values :");
printf("\nprice increment and quantity increment\n");
scanf("%f %d",&p_inc,&q_inc);
item=update(item,p_inc,q_inc); /*function call*/
printf("\nUpdate values of item:\n");
printf("Name :%s\n",[Link]);
printf("Price:%f\n",[Link]);
printf("Quantity :%d\n",[Link]);
val=mul(item); /*function call*/
printf("\nValue of the item=%f\n",val);
getch();
}
struct stores update(struct stores prod,float p,int q)
{
[Link]+=p;
[Link]+=q;
return(prod);
}
float mul(struct stores stock)
{
return([Link] * [Link]);
}
Example: Write a c program to simulate the multiplication of two fractions by passing entire
structure as an argument to a function.
#include<stdio.h>
struct fraction
{
int num;
int denom;
};
struct fraction multiply(struct fraction,struct fraction);
main()
{
struct fraction f1,f2,result;
clrscr();
printf("\nEnter numerator and denominator of first fraction:");
scanf("%d%d",&[Link],&[Link]);
printf("\nEnter numerator and denominator of second fraction:");
scanf("%d%d",&[Link],&[Link]);
result=multiply(f1,f2);
printf("\nThe result after multiplication of two fractions is:");
printf("\n%d / %d",[Link], [Link]);
}
struct fraction multiply(struct fraction x struct fraction y)
{
struct fraction r;
[Link]=[Link]*[Link];
[Link]=[Link]*[Link];
return r;
}
Passing structure by reference (call by reference): An address of structure variable can be passed
as an argument to the called function. If structure is passed by reference, any change made in
structure variable in the called function does reflect in original structure variable in the calling
function.
General format of sending address of a structure to the called function:
function name (&structure_variable_name);
The called function takes the fallowing form:
data type function name (struct_type *structvariablename)
{
-----------
-----------
}
Example: Example: program on passing address of a structure variable.
#include<stdio.h>
main( )
{
struct book
{
char title[25];
char author[25];
int no;
};
struct book b={“ RGM C Notes”,”DCSE”,9};
clrscr();
printf(“The book details before the function call”);
printf(%s\n %s\n %d\n”,[Link],[Link],[Link]);
display(&b);
printf(“The book details after the function call”);
printf(%s\n %s\n %d\n”,[Link],[Link],[Link]);
}
display(struct book *b)
{
b->no+=20;
}
Pointers to Structures: We know that the name of an array stands for the address of its 0 th element.
The same thing is applicable for the arrays of structure variables. The way we can have a pointer
pointing to an int, or a pointer pointing to a char, similarly we can have a pointer pointing to the
structure variables (Such pointers are known as structure pointers) but for accessing you have to use
arrow operator(->) or member selection operator and it is made up of minus and a greater than sign.
Consider the following declaration:
struct inventory
{
char name[30];
int number;
float price;
}product[2], *ptr;
This statement declares that, product as an array of 2 elements, each of the type struct inventory and
ptr as a pointer to the data objects of the type struct inventory.
The assignment statement would assign the address of 0 th element of product to ptr.
ptr = product;
That is, the pointer ptr points to product[0]. Its members can be accessed using the following
notation. ptr -> name;
ptr-
>number;
ptr->price;
The symbol -> is called as the arrow operator and it is comprised of a minus sign & a greater than
sign. Note that ptr-> is simply another way of writing product [0].
Whenever the pointer is incremented by one, it is made to point to the next record,i.e., product[1].
We could also use the following notation,
(*ptr).name to access the member name.
Note: The parenthesis around *ptr are necessary because, the member operator (.) has higher
precedence than the operator *.
While using the structures pointers, we should take care of the precedence of operators. The operators
->, “.‟, ( ), [ ] have the highest priority among the operators.
They bind very tightly with their operands. For example, consider the following
definition: struct xyz
{
int count;
float *p; /* Pointer inside the struct xyz */
} *ptr; /* struct xyz type pointer */
For the above definition, the statement,++ptr->count; increments count, not [Link], the
following statement,
(++ptr) -> count; increments ptr first, and then links count.
The statement
ptr ++ -> count; is legal and increments ptr after accessing count.
The following statements also behave in the similar fashion.
*ptr-> p fetches whatever p points.
*ptr -> p++ Increments p after accessing whatever it points to.
(*ptr -> p)++ Increments whatever p points.
*ptr++ -> p Increments ptr after accessing whatever it points to.
We are already discussed about passing of a structure as an argument to a function. We also saw an
example, where a function receives a copy of an entire structure and returns it after working on it. As
we mentioned earlier, this method is inefficient in terms of both, the execution speed and memory.
We can overcome this drawback by passing a pointer to the structure and then using this pointer to
work on the structure members.
Example: example program on structure pointers.
#include <stdio.h>
main( )
{
struct book
{
char title[25];
char author[25];
int no;
};
struct book b={“ RGM „C‟ Notes”,”DCSE”,9};
struct book *ptr;
ptr=&b;
printf(“%s %s %d\n”,[Link],[Link],[Link]);
printf(“%s %s %d\n”, ptr->tittle,ptr->author,ptr->no);
}
Output: RGM C Notes DCSE 9
RGM C Notes DCSE 9
Explanation: The first printf( ) is as usual way of accessing the members of the structure. The
second printf( ) however is peculiar. We cannot use [Link], [Link] and [Link] because ptr is not
a structure variable but it is a pointer to a structure, and the dot operator requires a structure variable
on its left. So, In such cases C provides an operator -> called as an arrow operator to refers the
structure elements.
Example: C Program to illustrate the use structure pointers.
struct invent
{
char name[20];
int number;
float price;
};
main( )
{
struct invent product[3], *p;
clrscr( );
printf(“\n INPUT \n\n”);
for( p = product; p<product+3; p++)
scanf(“%s %d %f”,p->name, &p->number, &p->price);
printf(“\nOUTPUT\n\n”);
p=product;
while(p < product +3)
{
printf(“%-20s %5d %11.5f\n”, p->name, p -> number, p ->price);
p++;
}
getch( );
}
Accessing Structure Members with Pointer:To access members of structure with

structure variable, we used the dot( .) Operator. But when we have a pointer of
structure type, we use arrow ->to access structure members.
#include<stdio.h>
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book b;
struct Book* ptr = &b;
ptr->name = "Dan Brown"; //Accessing Structure Members
ptr->price = 500;
}

#include<stdio.h>
struct team
{
char *name;
int members;
char captain[20];
}t1 = {"India",11,"Dhoni"} , *sptr = &t1;
main()
{
printf("\nTeam : %s",(*sptr).name);
printf("\nMemebers : %d",sptr->members);
printf("\nCaptain : %s",(*sptr).captain);
}

Example: write a program to implement the problem in example one using pointer notation.
#include<stdio.h>
#include<conio.h
> void main( )
{
struct student
{
int marks1,marks2,marks3;
}s1,s2;
struct student *std1,*std2;
clrscr( );
std1=&s1;
std2=&s2;
std1->marks1=55;
std1->marks2=66;
std1->marks3=80;
std2->marks1=60;
std2->marks2=85;
std2->marks3=78;
Printf(“marks obtained by 1st student: %d , %d and %d”,
std1->marks1,std1->marks2,std1->marks3);
Printf(“\n marks obtained by second student: %d and %d”,
std2->marks1,std2->marks2,std2->marks3);
getch( );
}
Example: implement the problem in example using pointer notation.
#include<stdio.h>
#include<conio.h
> void main()
{
struct student;
{
int marks1,marks2,marks3,sum;
float avg;
}s1;
struct student *std1;
clrscr();
std1=&s1;
Printf(Enter the marks obtained by the student in three subjects : “);
scanf(“%d%d%d “,&s1.marks1 ,&s1.marks2,&s1.marks3);
std1 ->sum=std->marks1+std1->marks2+std1->marks3;
std1->avg=(std1->marks1+std1->marks2+std1->marks3)/3;
Printf(“sum=%d\navg=%.2f”,std1->sum,std1->avg);
getch();
}
Size of structures: We normally use structures and arrays to create variables if larger sizes. The
actual size of these variables in terms of bytes may change form machine to machine. We may use
the unary operator sizeof() to tell us the size of a structure.
The expression,
sizeof(struct x)
will evaluate the number of bytes required to hold all the members of the structure x.
If y is a simple structure variable of type struct x, then the expression,
sizeof (y)
would also give the same [Link],if y is an array variable of type struct x.
Example: program to display the size of a structure variable.
#include<stdio.h>
#include<conio.h
> void main()
{
struct s
{
int a;
char b;
float c;
long d;
}s1;
Printf(“\n size of (s1)=%d”,sizeof(s1));
getch();
}
Example: program to display the size of a structure variable.
#include<stdio.h>
struct book
{
char bname[30];
int ssn;
int pages;
};
main()
{
struct book b1;
printf("\nSize of bname : %d",sizeof([Link]));
printf("\nSize of ssn :
%d",sizeof([Link])); printf("\
nSize of pages :
%d",sizeof([Link])); printf("\
nSize of Structure :
%d",sizeof(b1));
}

You might also like