0% found this document useful (0 votes)
4 views23 pages

Module 4 Function 46 68

This document discusses structures and unions in programming, highlighting the differences between arrays and structures, and explaining how to define, declare, and initialize structures. It covers accessing structure members, copying and comparing structure variables, and using arrays within structures. Additionally, it addresses the use of nested structures and methods for passing structures to functions.

Uploaded by

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

Module 4 Function 46 68

This document discusses structures and unions in programming, highlighting the differences between arrays and structures, and explaining how to define, declare, and initialize structures. It covers accessing structure members, copying and comparing structure variables, and using arrays within structures. Additionally, it addresses the use of nested structures and methods for passing structures to functions.

Uploaded by

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

UNIT – IV

CHAPTER X
STRUCTURES AND UNIONS

46
10.1 INTRODUCTION
• Arrays can be used to represent a • Structure is a method of packing
group of data items that are belongs to data of different types.
the same type. • A structure is a convenient method of
• Arrays are used to store large set of handling a group of related data items
data and manipulate them. of different data types.
• disadvantage of arrays is that all the
elements stored in an array are to be
of the same data type.
• If we need to use a collection of
different data type items it is not
possible using an array.
• When we require using a collection of
different data items of different data
types we can use a structure.

47
10.2 Array vs structures

1. An array is a collection of related data elements of same


type. Structure can have elements of different types.
2. An array is derived data type whereas Structure is user-
defined one.
3. Any array behaves like a built-in data type. All we have
to do is to declare an array variable and use it. But in the
case of a Structure, first, we have to design and declare
a data structure before the variables of that type are
declared and used.

48
10.3 DEFINING A STRUCTURE
Syntax struct book_bank
struct tag_name {
{ char title[20];
data type member1; char author[15];
data type member2; int pages;
… float price;
… };
};
Note • Create a structure Book_bank to store book
details.
1. The template is terminated with a
semicolon. • The keyword struct declares a structure to
holds the details of four fields namely title,
2. While the entire definition is considered as author, pages and price.
a statement, each member is declared
independently for its name and type in a • These are members or elements of the
separate statement inside the template. structures.
3. The tag name can be used to declare • Each member may belong to different or
structure variables of its type, later in the same data type.
program. • The tag name can be used to define objects
that have the tag names structure.
• The structure we just declared is not a
variable by itself but a template for the
structure.

49
10.4 DECLARING STRUCTURE
VARIABLE
To access structure item, we require to We can declare structure variables using
create the tag name any where in the
structure variable (object). program.
• A structure variable declaration is Example
similar to the declaration of variables struct lib_books book1,book2,book3;
of any other data types.
It includes the following elements: • Declares book1,book2,book3 as
1. The keyword struct. variables of type struct lib_books
2. The structure tag name. each declaration has four elements of
3. List of variable names separated by the structure lib_books.
names. • Structures do not occupy any memory
4. A terminating semicolon. until it is associated with the structure
variable such as book1.
Syntax
struct structure_name variable_name;

50
We can also combine both template
• Declares book1, book2, book3 as
declaration and variables declaration
structure variables representing 3
in one statement.
books but does not include a tag name
Example for use in the declaration.
struct lib_books • This approach is not recommended
{ for the two reasons.
char title[20]; 1. Without tag name, we cannot use it
char author[15]; for future declarations.
int pages; 2. Normally, structure definitions appear
float price; at the beginning of the program file,
before any variables or functions are
} book1,book2,book3;
defined. They may also appear before
The use of tag name is optional. the main, along with macro
Example definitions, such as #define. In such
struct cases, the definition is global and can
{ be used by other functions as well.



} book1, book2, book3 ;
51
10.5 Type-Defined Structures
Syntax
typedef struct
{
--------
type member1;
type member2;
--------
}type name;

• The type-name represents structure definition associated with it and therefore, can
be used to declare structure variables as
type-name variable1,variable2,…………….;
Note
1. The name type-name is the type definition name ,not a variable.
2. We cannot define a variable with typedef declaration.

52
10.6 ACCESSING STRUCTURE MEMBERS
• The link between a member and a Or We can use scanf statement to assign
variable is established using the values like
member selection operator ‘.’ which scanf(“%s”,[Link]);
is known as dot operator or period scanf(“%d”,&[Link]);
operator.
Example
[Link]
• is the variable representing the price
of book1 and can be treated like any
other ordinary variable.
• we can assign variables to the
members of book1
strcpy([Link],”basic”);
strcpy([Link],”Balagurusamy”);
[Link]=250;
[Link]=285.0;

53
Example program scanf("%s",[Link]);
#include<stdio.h> printf("Enter the roll number of
#include<conio.h> student2:");
struct student scanf("%d",&[Link]);
{ printf("Enter the marks of student2:");
char name[20]; scanf(“%d",&[Link]);
int num; printf(“Students Details\n");
int mark; printf(“Student 1 details\n”);
}; printf("%s\n",[Link]);
void main() printf("%d\n",[Link]);
{ printf(“%d\n",[Link]);
struct student s1,s2; printf(“Student 2 details\n”);
clrscr(); printf("%s\n",[Link]);
printf("Enter the name of student1:"); printf("%d\n",[Link]);
scanf("%s",[Link]); printf(“%d",[Link]);
printf("Enter the roll number of getch();
student1:"); }
scanf("%d",&[Link]);
printf("Enter the marks of student1:");
scanf(“%d",&[Link]);
printf("Enter the name of student2:");

54
10.7 STRUCTURE INITIALIZATION
• A structure variable can be initialized Example2
at compile time. main()
Example 1 {
main() struct st_record
{ {
struct int weight;
{ float height;
int weight; };
float height; struct st_record student1={50,170.26};
} student={50,170.26}; struct st_record student2={60,180.75};
………… …………
………… …………
} }
• This assigns 50 to [Link] and
170.26 to [Link].
• There is one-to-one correspondence
between the members and their
initializing values.

55
Example 3 1. The name of the variable to be
struct st_record declared.
{ 2. The assignment operator =.
int weight; 3. A set of values for the members of
float height; the structure variable, separated by
}student1={50,170.26}; commas and enclosed in braces.
4. A terminating semicolon.
main()
{ Rules for initializing structures
struct st_record student2={60,180.75}; 1. We cannot initialize the individual
………… members inside the structure
………… template.
} 2. The order of values enclosed in
• The c language does not permit the braces must match the order of
initialization of individual structure members in the structure definition.
members within the templates.
• The initialization must done only in 3. It is permitted to have a partial
the declaration of the actual variables. initialization. We can initialize only
• The compile-time initialization of a the first few members and leave the
structure variable must have the remaining blank. The uninitialized
following elements. members should be only at the end of
1. The keyword struct the list.
2. The structure tag_name.
4. The uninitialized members will be
56
assigned default values.
10.8 COPYING & COMPARING STRUCTURE VARIABLES
copy void main()
• Two variables of the same structure type can be {
copied .
int x;
Example
• If student1 and student2 belong to the same struct class stud1={101, “anu”,89};
structure then struct class stud2={102, “banu”,80};
student1=student2; struct class stud3;
student2= student1;
stud3=stud2;
Comparision x= (([Link]==[Link]) && ([Link] ==
• The following statements are not permitted in c.
[Link]))?1:0;
student1 == student2
student1 != student2 if (x=1)
• C does not permitted any logical operators on {
structure variables. printf(“\n student2 and student3 same\n”);
• We can compare members individually.
printf(“%d%s%d”,[Link],[Link],[Link])
;
structure class
{ }
int no; else
char name[20]; {
int marks; printf(“student2 and student3 are different”);
};
}
}

57
10.9 ARRAYS OF STRUCTURES
• Declaring an array of structure is same as Example
declaring an array of fundamental types. struct student
• An array is a collection of elements of the {
same type. char name[20];
• In an array of structures, each element of an int num;
array is of the structure type.
• An array of structure is stored inside the int mark;
memory in the same way as a multi- };
dimensional array. struct student stud[10];

Syntax
struct tag_name
{
data type member1;
data type member2;


};
struct tag-name struct_array[size];

58
EXAMPLE
#include<stdio.h> printf(“Enter the name of the student %d :”, i+1)
#include<conio.h> scanf(“%s”, stud[i].name);
struct student printf(“Enter the marks of the student %d :”, i+1)
{ scanf(“%d”, &stud[i].mark);
char name[20]; }
int num; for (i=0;i<n;i++)
int mark; {
}; printf(“[Link] of the student %d : %d”,
struct student stud[10]; i+1,stud[i].num);
void main() printf(“Name of the student %d : %s”,
{ i+1,stud[i].name);
int i,n; printf(“Marks of the student %d : %d”,
i+1,stud[i].mark);
clrscr(); }
printf(“\n Enter the no. of students in a class:”); getch();
scanf(“%d”, &n); }
printf(“Enter the students detials one by one\n”);
for (i=0;i<n;i++)
{
printf(“Enter the [Link] of the student %d :”, i+1)
scanf(“%d”, &stud[i].num);

59
10.10 ARRAYS WITHIN STRUCTURES
• C permits the use of arrays as structure printf(“Enter the name of the student %d :”, i+1)
members. scanf(“%s”, stud[i].name);
Example printf(“Enter the marks of the student %d :”, i+1)
stud[i].total=0;
#include<stdio.h> for (j=0;j<3;j++)
#include<conio.h> {
struct student
scanf(“%d”, &stud[i].mark[j]);
{
char name[20]; stud[i].total= stud[i].total+stud[i].mark[j];
int num; }
int mark[3]; }
int total; for (i=0;i<n;i++)
};
{
struct student stud[10];
void main() printf(“\[Link] of the student %d : %d”,
{ i+1,stud[i].num);
int i,n,j; printf(“\nName of the student %d : %s\n”,
clrscr(); i+1,stud[i].name);
printf(“\n Enter the no. of students in a class:”); for (j=0;j<3;j++)
scanf(“%d”, &n); printf(“Marks of the student %d \t: %d”,
printf(“Enter the students detials one by one\n”); i+1,stud[i].mark[j]);
for (i=0;i<n;i++)
printf(“\nTotal marks of the student %d : %d”,
{
i+1,stud[i].total);
printf(“Enter the [Link] of the student %d :”, i+1)
scanf(“%d”, &stud[i].num); }
getch();
}
60
10.11 STRUCTURES WITHIN STRUCTURES
• Structure within a structure is called
nested structure. • The members contained in the inner
Example structure namely da, hra and cca can
struct salary be reffered as
{
char name[20]; [Link];
char dept[30]; [Link];
struct [Link];
{
int da; • A inner-most member in a nested-
structure can be accessed by chaining
int hra; all the concerned structures variables
int cca; with member using dot operator.
}allowance;
} employee;

• The salayy structure contains a


member named allowance, which
itself is a structure with three
members.

61
10.12 STRUCTURES & FUNCTIONS
There are 3 methods to transferred structure • The general format of sending a copy of a
from one function to another. structure to the called function is
1. Pass each member of structure as an actual function_name(structure_variable_name);
argument of the function call. The actual • The called function format
arguments are then treated independently data_type
like ordinary variables. This is the most function_name(struct_variable_name)
elementary method and becomes
unmanageable and inefficient when the {
structure size is large. ………….
2. Passing of a copy of the entire structure to ………….
the called function. Since the function is return(expression);
working on a copy of the structure, any }
changes to structure members within the Note
function are not reflected in the original
structure. Therefore the necessary for the 1. The called function must be declared for
function to return the entire structure back its type, appropriate to the data type it is
to the calling function. expected to return.
3. Using pointers to pass the structure as an 2. The structure variable used as the actual
argument. argument and the corresponding formal
parameter in the called function must be of
the same struct type.
62
3. The return statement is necessary only void print_struct(struct student stu);
when the function is returning some data
back to the calling function. The void main()
expression may be any simple variable or {
structure variable or an expression using struct student stu = {"George", 10, 69};
simple variables print_struct(stu);
4. When a function returns a structure, it return 0;
must be assigned to a structure of identical }
type in the calling function.
void print_struct(struct student stu)
5. The called functions must be declared in
the calling function appropriately. {
printf("Name: %s\n", [Link]);
Example printf("Roll no: %d\n", stu.roll_no);
#include<stdio.h> printf("Marks: %d\n", [Link]);
#include<conio.h> printf("\n");
/* structure is defined above all functions so it }
is global. */
struct student
{
char name[20];
int roll_no;
int marks;
};

63
10.13 UNIONS
• A union is a special data type available in • The union tag is optional and each
C that allows to store different data types member definition is a normal variable
definition, such as int i; or float f; or any
in the same memory location. other valid variable definition.
• We can define a union with many • At the end of the union's definition, before
members, but only one member can the final semicolon, you can specify one or
contain a value at any given time. more union variables but it is optional.
• Unions provide an efficient way of using Example
the same memory location for multiple-
purpose. union Data
Defining a Union {
union [union tag] int i;
{ float f;
member definition; char str[20];
} data;
member definition;
... • A variable of Data type can store an
member definition; integer, a floating-point number, or a
string of characters.
} [one or more union variables];

64
• It means a single variable, i.e., same #include <stdio.h>
memory location, can be used to store #include <string.h>
multiple types of data. union Data
• We can use any built-in or user defined {
data types inside a union based on your int i;
requirement.
float f;
• The memory occupied by a union will be
char str[20];
large enough to hold the largest member of
the union. };
Example int main( )
• Data type will occupy 20 bytes of {
memory space because this is the union Data data;
maximum space which can be occupied by data.i = 10;
a character string. data.f = 220.5;
Accessing Union Members strcpy( [Link], "C Programming");
• To access any member of a union, we use printf( "data.i : %d\n", data.i);
the member access operator (.).
printf( "data.f : %f\n", data.f);
• The member access operator is coded as a
printf( "[Link] : %s\n", [Link]);
period between the union variable name
and the union member that we wish to return 0;
access. }
• The keyword union to define variables of Output: [Link] : C Programming
union type.
65
10.14 BIT FIELDS
• A bit field is a set of adjacent bits whose • A signed bit field should have at least 2
size can be from 1 to 16 bits length. bits(one bit for sign).
• A word can therefore be divided into a • The field name is followed by a colon.
number of bit fields. • The bit-length is decided by the range of
• The name and size of bit fields are defined value to be stored.
using structure. • The largest value that can be stored is 2 n-,
Syntax where n is bit-length.
struct tag-name • The internal representation of bit fields is
{ machine dependent.
data-type name:bit-length; • It depends on the size of int and ordering of
data-type name:bit-length; bits.
…………….. 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
……………..
data-type name:bit-length;
};
• The data type is either signed int or name n ……………………. name2 name1
unsigned int and the bit-length is the no. of
bits used for a specified name.

66
Note Example
1. The first field always starts with the first #include <stdio.h>
bit of the word. #include <string.h>
2. A bit field cannot overlap integer struct
boundaries. Ie. The sum of lengths of all {
the fields in a structure should not be
more than the size of a word. In case, it unsigned int age : 3;
is more, the overlapping field is } Age;
automatically forced to the beginning of int main( )
the next word. {
3. There can be unnamed fields declared [Link] = 4;
with size. printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
4. There can be unused bits in the word. printf( "[Link] : %d\n", [Link] );
5. We cannot take the address of a bit field [Link] = 7;
variable. This means we cannot use
scanf() function to read values into bit printf( "[Link] : %d\n", [Link] );
fields. We can neither use pointer to [Link] = 8;
access the bit fields. printf( "[Link] : %d\n", [Link] );
6. Bit fields cannot be arrayed. return 0;
7. Bit fields should be assigned values that }
are within the range of their size.. If we
try to assign larger values, behaviour
would be unpredicted.
67
References
1. E. Balagurusamy, ”Programming in ANSI C”, Seventh Edition, McGraw Hill Education India
Private Ltd, 2017.
2. [Link]
3. [Link]

68

You might also like