Structure Union Notes
Structure Union Notes
Structures
STRUCTURES
A structure is a collection of variables under a single name and
provides a convenient way of grouping several pieces of related
information together.
1
25-02-2022
DEFINING A STRUCTURE
Data_type2 member_name2;
} struct_var1, struct_var2;
The structure tag / structure name is optional and each member definition is a
normal variable definition, such as int i; or float f; or any other valid variable
definition. At the end of the structure's definition, before the final semicolon, you
can specify one or more structure variables but it is optional.
2
25-02-2022
struct employee
{ int id;
char name[20];
float salary;
};
Here, struct is the
keyword; employee is the
name of the
structure; id, name,
and salary are the members or
fields of the structure. Let's
understand it by the diagram:
This image shows the memory allocation of the structure employee that
is defined in the example.
3
25-02-2022
struct books {
char title[50]; struct books {
char author[50]; char title[50];
char subject[100]; char author[50];
int book_id; char subject[100];
} book1; int book_id;
};
struct books book1;
4
25-02-2022
10
5
25-02-2022
11
12
6
25-02-2022
13
2. The assignment operator assigns (i.e. copies) values of all the members of
the structure object on its right side to the corresponding members of the
structure variable on its left side one by one. It performs member-by-
member copy.
14
7
25-02-2022
Pointers to Structures
You can define pointers to structures in the same way as you define pointer
to any other variable −
To find the address of a structure variable, place the '&'; operator before
the structure's name as follows −
struct_pointer = &book1;
struct_pointer->title;
15
The operator is used along with a pointer variable. That is, it stores the value at the
location(variable) to which the pointer/object points.
16
8
25-02-2022
17
printf(“%d\n”,pstu->stuno);
18
9
25-02-2022
ARRAY OF STRUCTURES
It is possible to create an array whose elements are of structure type. Such an array is
known as an array of structures. An array of structures is declared in the same way as any
other kind of array is declared.
#include<stdio.h> }
#include <string.h> printf("\nStudent Information List:");
19
20
10
25-02-2022
21
You can pass a structure as a function argument in the same way as you pass
any other variable or pointer.
22
11
25-02-2022
struct phone_entry
{
struct name pname; //nested structure
char mno[10];
};
23
➢It is even possible to define a structure type within the declaration list of another
structure type definition.
#include<stdio.h>
struct phone_entry Output:
{ struct name Enter the mobile number of Anil Kumar
{ 9810000000
char fnam[20];
char lnam[20]; Phone book entries are:
} pnam; Anil Kumar: 9810000000
char mno[10];};
main()
{
struct phone_entry per1={"Anil","Kumar"};
printf("Enter the mobile number of %s %s\n",per1.pnam.fnam, per1.pnam.lnam);
gets(per1.mno);
printf("\nPhone book entries are:\n");
printf("%s %s:\t%s\n", per1.pnam.fnam, per1.pnam.lnam, per1.mno);}
24
12
25-02-2022
#include<stdio.h>
typedef unsigned int unit;
main()
{
unit i,j; Value of i is :10
i=10; Value of j is :20
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
}
25
You can use typedef to give a name to your user defined data types as well.
For example, you can use typedef with structure to define a new data type
and then use that data type to define structure variables directly as follows −
26
13
25-02-2022
27
UNION
A union is a collection of one or more variables, possibly of different types.
2. Declaring union objects: Objects of a union type can be declared either at the
time of union type definition or after the union type definition in a separate
declaration statement.
28
14
25-02-2022
This implies that although a union may contain many members of different
types, it cannot handle all the members at the same time. A union is
declared using the union keyword.
29
3. Size of a union object or union type: Upon the declaration of a union object,
the amount of memory allocated to it is the amount necessary to contain its
largest member.
4. Address-of a union object: The members of a union object are stored in the
memory in such a way that they overlap each other. All the members of a union
object start from the same memory location.
5. Initialization of a union object: Since the members of a union object share the
same memory, the union object can hold the value of only one of its member at a
time.
#include<stdio.h>
union variables Output:
{ Compilation error “Declaration syntax error in
char a; function main()”
int b;
float c;} ;
main()
{union variables var={‘A’, 2, 2.5};
printf(“The values of the members are %c %d %f”, var.a, var.b, var.c); }
30
15
25-02-2022
Explanation:
Here, we created a union MyUnion that contains two members num1 and num2.
The union allocates space for only one member at a time. Then we created the
union variable UN in the main() function. After that, we get the size of the union
using the sizeof() operator, and set the value of variables one by one, and print the
value of variables on the console screen.
31
Struct Union
The struct keyword is used to define a structure. The union keyword is used to define union.
When the variables are declared in a structure, the When the variable is declared in the union, the
compiler allocates memory to each variables compiler allocates memory to the largest size
member. The size of a structure is equal or greater variable member. The size of a union is equal to the
to the sum of the sizes of each data member. size of its largest data member size.
Each variable member occupied a unique memory Variables members share the memory space of the
space. largest size variable.
Changing the value of a member will not affect Changing the value of one member will also affect
other variables members. other variables members.
Each variable member will be assessed at a time. Only one variable member will be assessed at a
time.
We can initialize multiple variables of a structure at In union, only the first data member can be
a time. initialized.
All variable members store some value at any point Exactly only one data member stores a value at any
in the program. particular instance in the program.
The structure allows initializing multiple variable Union allows initializing only one variable member
members at once. at once.
It is used to store different data type values. It is used for storing one at a time from different
data type values.
It allows accessing and retrieving any data member It allows accessing and retrieving any one data
at a time. member at a time.
32
16
25-02-2022
33
day = Wed; 2
printf("%d",day);
}
In the above example, we declared “day” as the variable and the
value of “Wed” is allocated to day, which is 2. So as a result, 2 is
printed.
34
17
25-02-2022
35
• The enumeration definition can optionally have the storage class specifier
and type qualifiers.
• The enumeration definition is a statement and must be terminated with a
semicolon.
#include<stdio.h>
enum CARS {alto, omni, esteem=3, wagonR, swift=1, dzire};
main()
{
printf(“The value of various enumeration constants are:\n”);
printf(“%d %d %d %d %d %d”, alto, omni, esteem, wagonR, swift,
dzire);
}
Output:
The values of various enumeration constants are:
013412
36
18
25-02-2022
As it can be seen that the length (size) of the array above made is 9. But what
if there is a requirement to change this length (size).
37
For Example,
❑If there is a situation where only 5 elements are needed to
be entered in this array. In this case, the remaining 4 indices
are just wasting memory in this array. So, there is a
requirement to lessen the length (size) of the array from 9
to 5.
❑Take another situation. In this, there is an array of 9
elements with all 9 indices filled. But there is a need to
enter 3 more elements in this array. In this case, 3 indices
more are required. So the length (size) of the array needs to
be changed from 9 to 12.
38
19
25-02-2022
They are:
39
malloc() function
The “malloc” or “memory allocation” method in C is
used to dynamically allocate a single large block of
memory with the specified size. It returns a pointer of
type void which can be cast into a pointer of any form.
It doesn’t Initialize memory at execution time so that it
has initialized each block with the default garbage
Syntax:
value initially.
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(200);
or
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 2 bytes, this statement will allocate 200 bytes of
memory and the pointer ptr holds the address of the first byte in the
allocated memory.
40
20
25-02-2022
41
42
21
25-02-2022
calloc() function
1) “calloc” or “contiguous allocation” method in C is
used to dynamically allocate the specified number of
blocks of memory of the specified type. it is very
much similar to malloc() but has two different points
and these are:
• It initializes each block with a default value ‘0’.
• It has two parameters or arguments as compared to
malloc().
Syntax: ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
43
44
22
25-02-2022
C free() function
▪ “free” function in C is used to dynamically de-allocate
the memory. The memory allocated using functions
malloc() and calloc() is not de-allocated on their own.
▪ Hence the free() function is used, whenever the
dynamic memory allocation takes place.
▪ It helps to reduce wastage of memory by freeing it.
Syntax:
free(ptr);
45
46
23
25-02-2022
47
Use of realloc()
Size of dynamically allocated memory can be changed by using
realloc().
▪ realloc deallocates the old object pointed to by ptr
and returns a pointer to a new object that has the
size specified by size.
▪ The contents of the new object is identical to
that of the old object prior to deallocation, up to
the lesser of the new and old sizes. Any bytes in
the new object beyond the size of the old object
have uncertain values.
IMPORTANT POINT:
realloc() should only be used for dynamically allocated memory. If the
memory is not dynamically allocated, then behavior is undefined.
48
24
25-02-2022
Use of realloc()
#include <stdio.h> ptr_new = (int *)realloc(ptr,
#include <stdlib.h> sizeof(int)*3);
int main() *(ptr_new + 2) = 30;
{
int *ptr = (int *)malloc(sizeof(int)*2); for(i = 0; i < 3; i++)
int i; printf("%d ", *(ptr_new + i));
int *ptr_new; }
*ptr = 10;
*(ptr + 1) = 20;
10 20 30
49
Use of realloc()
#include <stdio.h> // rellocating the memory
#include <stdlib.h> ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated
main() { memory:\n");
int *ptr, i , n1, n2; for(i = 0; i < n2; ++i)
printf("Enter size: "); printf("%u \n", ptr + i);
scanf("%d", &n1); free(ptr);
}
ptr = (int*) malloc(n1 * sizeof(int)); Enter size: 2
Addresses of previously allocated memory:
printf("Addresses of previously 26855472
allocated memory:\n"); 26855476
for(i = 0; i < n1; ++i)
printf("%u\n",ptr + i); Enter the new size: 4
Addresses of newly allocated memory:
26855472
printf("\nEnter the new size: ");
26855476
scanf("%d", &n2); 26855480
26855484
50
25
25-02-2022
51
52
26
25-02-2022
END
53
27