Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views27 pages

Structure Union Notes

The document provides an overview of structures in C programming, explaining their definition, declaration, and usage for grouping related data. It covers how to define a structure, initialize its members, access them using dot and arrow operators, and pass structures as function arguments. Additionally, it discusses the creation of arrays of structures and the assignment of structure objects.
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)
7 views27 pages

Structure Union Notes

The document provides an overview of structures in C programming, explaining their definition, declaration, and usage for grouping related data. It covers how to define a structure, initialize its members, access them using dot and arrow operators, and pass structures as function arguments. Additionally, it discusses the creation of arrays of structures and the assignment of structure objects.
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
You are on page 1/ 27

25-02-2022

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.

It can be used for the storage of heterogeneous data.

Three important tasks of working with structures:

❑ Defining a structure type i.e. creating a new type.


❑ Declaring variables and constants (i.e. objects) of the newly
created type.
❑ Using and performing operations on the objects of the structure
type.

1
25-02-2022

DEFINING A STRUCTURE

To define a structure, you must use the struct statement.


The struct statement defines a new data type, with more
than one member. The format of the struct statement is
as follows − struct structName
{
// structure definition
Data_type1 member_name1;
Data_type2 member_name2;

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.

Description of the Syntax


❑ Keyword struct: The keyword struct is used at the beginning
while defining a structure in C. Similar to a union, a
structure also starts with a keyword.
❑ structName: This is the name of the structure which is
specified after the keyword struct.
❑ data_Type: The data type indicates the type of the data
members of the structure. A structure can have data
members of different data types.
❑ member_name: This is the name of the data member of the
structure. Any number of data members can be defined
inside a structure. Each data member is allocated a separate
space in the memory.

2
25-02-2022

Let's see the example to define a structure for an entity employee in c.

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

We can declare a variable for the structure so that we can access


the member of the structure easily. There are two ways to declare
structure variable:
• By struct keyword within main() function
• By declaring a variable at the time of defining the structure.

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;

How to Initialize Structure Members?

Structure members cannot be initialized like other


variables inside the structure definition. This is because
when a structure is defined, no memory is allocated to
the structure’s data members at this point. Memory is
only allocated when a structure variable is declared.
Consider the following code snippet.
struct rectangle
{
// structure definition
int length = 10; // COMPILER ERROR: cannot initialize members here.

int breadth = 6; // COMPILER ERROR: cannot initialize members here.


};
A compilation error will be thrown when the data members of the structure are
initialized inside the structure.

4
25-02-2022

To initialize a structure’s data member, create a structure


variable. This variable can access all the members of the
structure and modify their values. Consider the following
example which initializes a structure’s members using the
structure variables.
int main() In this example, the structure variable
{ my_rect is modifying the data
struct rectangle members of the structure. The data
members are separately available to
{
my_rect as a copy. Any other structure
// structure definition variable will get its own copy, and it
int length; will be able to modify its version of the
int breadth; length and breadth.
};
struct rectangle my_rect; // structure variables;
my_rect.length = 10;
my_rect.breadth = 6;
}

accessing members of an object of a structure


type

The members of a structure object can be accessed by using:


➢Direct member access operator (i.e. ., also known as dot
operator).
➢Indirect member access operator† (i.e. ->, also known as arrow
operator)

Important points about the use of dot operator:


1. The dot operator accesses a structure member via structure
object name while arrow operator accesses a structure member
via pointer to the structure.
The general form of using dot operator is:
structure_variable_name.structure_member_name
2. The dot operator is a binary operator

10

5
25-02-2022

Accessing Structure Members

To access any member of a structure, we use the


member access operator (.)
The member access operator is coded as a period
between the structure variable name and the
structure member that we wish to access.

You would use the keyword struct to define variables


of structure type. The following example shows how
to use a structure in a program −

11

Accessing Structure Members


#include <stdio.h> /* print book1 info */
#include <string.h> printf( "Book 1 title : %s\n", book1.title);
printf( "Book 1 author : %s\n", book1.author);
main( ) { printf( "Book 1 subject : %s\n", book1.subject);
struct books { printf( "Book 1 book_id : %d\n", book1.book_id);
char title[50];
char author[50]; /* print Book2 info */
char subject[100]; printf( “\nBook 2 title : %s\n", book2.title);
int book_id; printf( "Book 2 author : %s\n", book2.author);
}; printf( "Book 2 subject : %s\n", book2.subject);
struct books book1; printf( "Book 2 book_id : %d\n", book2.book_id);
/* Declare book1 of type book */ }
struct books book2;
/* Declare book2 of type book */ Book 1 title : Let Us C
/* book 1 specification */
Book 1 author : Yashavant Kanetkar
strcpy( book1.title, "Let Us C"); Book 1 subject : C Programming
strcpy( book1.author, "Yashavant Kanetkar"); Book 1 book_id : 6495407
strcpy( book1.subject, "C Programming");
book1.book_id = 6495407;
Book 2 title : C Programming Language
/* book 2 specification */ Book 2 author : Dennis Ritchie
strcpy( book2.title, "C Programming Language"); Book 2 subject : C Language
strcpy( book2.author, "Dennis Ritchie");
strcpy( book2.subject, " C Language");
Book 2 book_id : 6495700
book2.book_id = 6495700;

12

6
25-02-2022

assigning a structure object to structure


variable
Like simple variables, a structure variable can be assigned with or initialized
with another structure object of the same structure type.
#include<stdio.h>
struct book //structure definition
{
char title[25]; Output:
char author[20]; Godan by Munshi Premchand is of Rs. 200
int price; Godan by Munshi Premchand is of Rs. 200
}; Godan by Munshi Premchand is of Rs. 200
main()
{struct book b1={“Godan”, “Munshi Premchand”, 200};
struct book b2=b1;
struct book b3;
b3=b2; //Assigning a structure variable to a structure variable
printf(“%s by %s is of Rs. %d rupees\n”, b1.title, b1.author, b1.price);
printf(“%s by %s is of Rs. %d rupees\n”, b2.title, b2.author, b2.price);
printf(“%s by %s is of Rs. %d rupees\n”, b3.title, b3.author, b3.price);
}

13

Important points about the structure variable assignment:

1. A structure variable can be assigned with or initialized with a structure


object of the same type. If the type of assigning or initializing structure
object is not same as the type of structure variable on the left side of
assignment operator, there will be a compilation error.

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.

3. The structure assignment does not copy any padding bits.

4. Due to member-by-member copy behavior of the assignment operator on


the structure variables, structure objects can be passed by value to
functions†† and can also be returned from functions.

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 −

struct books *struct_pointer;


Now, you can store the address of a structure variable in the above defined
pointer variable.

To find the address of a structure variable, place the '&'; operator before
the structure's name as follows −
struct_pointer = &book1;

To access the members of a structure using a pointer to that structure, you


must use the → operator as follows −

struct_pointer->title;

15

This operator(->) is built using a minus(-) operator and a


greater than(>) relational operator. Moreover, it helps us
access the members of the struct or union that a pointer
variable refers to.

Let us now focus on the structure of Arrow operator in C.

Syntax of Arrow operator(->)


Have a look at the below syntax!

(pointer variable)->(variable) = value;

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

Difference Between Dot and Arrow Operators in C

In this example, we have a structure student with member stuno of


integer type.
The structure variable is stu1.
In the program, we have a pointer to the student structure by name
pstu.
Now consider the two print statements in the program as shown
below-

The declaration *pstu.stu1 uses the dot operator.


The above declaration produces an error.
The error generates because the dot operator has the
highest precedence than the star operator.
The C compiler will consider the statement as *(pstu.stu1)
This declaration will produce an error.
The correct way to declare to access the members of the
structures using pointers is *(pstu).stu1.

17

Difference Between Dot and Arrow Operators in C


As paratheses are cumbersome all the time, C is providing the arrow operator to access
the elements using pointers.
The declaration *(pstu).stu1 can also be done by using pstu->stu1.
Instead of the parentheses and star operator, we can use the arrow operator.

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:");

struct student{ for(i=0;i<5;i++)


int rollno; {
char name[10]; printf("\nRollno:%d, Name:%s",st[i].rollno,
}; st[i].name);
main(){ }
int i; }
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);

19

Enter Records of 5 students


Enter Rollno:1
Enter Name:Rohan
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Rohan
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz

20

10
25-02-2022

Structures as Function Arguments


You can pass a structure as a function argument in the same way as you pass
any other variable or pointer.

#include <stdio.h> /* print Book1 info ( Function Call )*/


#include <string.h> printBook( book1 );
struct books { }
char title[50];
char author[50]; /* function definition */
char subject[100]; printBook( struct books book )
int book_id; {
};
/* function declaration */ printf( "Book title : %s\n", book.title);
printBook( struct books book ); printf( "Book author : %s\n", book.author);
main( ) { printf( "Book subject : %s\n", book.subject);
/* Declare Book1 of type Book */ printf( "Book book_id : %d\n", book.book_id);
struct books book1; }
/* book 1 specification */
strcpy( book1.title, "Let Us C");
strcpy( book1.author, "Yashavant Kanetkar");
strcpy( book1.subject, "C Programming"); Book title : Let Us C
Book author : Yashavant Kanetkar
book1.book_id = 6495407; Book subject : C Programming
Book book_id : 6495407

21

You can pass a structure as a function argument in the same way as you pass
any other variable or pointer.

#include <stdio.h> /* print Book1 info by passing address of Book1 */


#include <string.h> printBook( &book1 );
struct books { }
char title[50];
char author[50]; /* function definition */
char subject[100]; printBook( struct books *sptr )
int book_id; {
}; printf( "Book title : %s\n", sptr->title);
/* function declaration */ printf( "Book author : %s\n", sptr ->author);
printBook( struct books* ); printf( "Book subject : %s\n", sptr ->subject);
main( ) printf( "Book book_id : %d\n", sptr->book_id);
{ }
struct books book1;
Book title : Let Us C
/* Declare Book1 of type Book */
Book author : Yashavant Kanetkar
/* book 1 specification */ Book subject : C Programming
strcpy( book1.title, "Let Us C"); Book book_id : 6495407
strcpy( book1.author, "Yashavant Kanetkar");
strcpy( book1.subject, "C Programming");
book1.book_id = 6495407;

22

11
25-02-2022

STRUCTURES WITHIN STRUCTURES (NESTED


STRUCTURES)
A structure can be nested within another structure. Nested structures are
used to create complex data types.
Declaration is as follows:
struct name
{
char fnam[20];
char lnam[20];
};

struct phone_entry
{
struct name pname; //nested structure
char mno[10];
};

23

Important points about nested structures:


➢The nested structures contain the members of other structure type. The structure
types used in the structure definition should be complete.

➢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

The C language contains the typedef keyword to allow


users to provide alternative names for the primitive (e.g.,​
int) and user-defined​ (e.g struct) data types.
Remember, this keyword adds a new name for some existing data type
but does not create a new type.

#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 −

#include <stdio.h> printf("ID of the first employee is : %d\n",


typedef struct employee e1.id);
{ printf("Salary of the second employee is :
int salary; %d\n", e2.salary);
int id; printf("ID of the second employee is : %d\n",
}emp; e2.id);
int main() }
Tutorial: typedef using struct!
{ Salary of the first employee is : 14000
emp e1,e2; ID of the first employee is : 1
e1.salary = 14000; Salary of the second employee is : 12000
e1.id = 1; ID of the second employee is : 2
e2.salary = 12000;
In this example, we have declared variable emp
e2.id = 2; of type struct employee.
printf("Tutorial: typedef using struct!\n"); We can create variables using the emp variable
printf("Salary of the first employee is : %d\n", of type struct employee. typedef keyword
e1.salary); reduces the length of the code and complexity of
data types. It also helps in understanding the
program.

26

13
25-02-2022

C program to add two distances


in feet and inches using structure
#include <stdio.h> }
struct distance{ main()
int feet;
int inch; { struct distance d1,d2;
}; printf("Enter first distance in feet & inches:
addDistance(struct distance d1,struct ");
distance d2) scanf("%d%d",&d1.feet, &d1.inch);
{
struct distance d3; printf("Enter second distance in feet &
d3.feet= d1.feet + d2.feet; inches: ");
d3.inch= d1.inch + d2.inch;
d3.feet= d3.feet + d3.inch/12; scanf("%d%d",&d2.feet, &d2.inch);
/*add two distances*/
//1 feet has 12 inches
d3.inch= d3.inch%12; addDistance(d1,d2);
printf("\nTotal distance- Feet: %d, Inches: } Enter first distance in feet & inches: 8 9
%d",d3.feet,d3.inch); Enter second distance in feet & inches: 7 8

Total distance- Feet: 16, Inches: 5

27

UNION
A union is a collection of one or more variables, possibly of different types.

The only difference between structures and unions is in the terms


of storage of their members. In structures, separate memory is
allocated to each member, while in unions, all the members of an
object share the same memory.
Operations on union objects: All the operations on union objects are applied in
the same way as they are applied on the structure objects.
Important points about unions:
1. Defining a union type: A union type is defined in the same way as a structure
type, with only difference that the keyword union is used instead of the
keyword struct .

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

// C program to find the size of union


un.num1 = 10;
#include <stdio.h> printf("\nNum1: %d, Num2: %f",
un.num1, un.num2);
union MyUnion {
int num1; un.num2 = 10.34;
float num2; printf("\nNum1: %f, Num2: %f",
}; un.num1, un.num2);
}
int main()
{ Size of union: 4
union MyUnion un; Num1: 10, Num2: 0.000000
Num1: 0.000000, Num2: 10.340000
printf("Size of union: %ld",
sizeof(un));

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

Enumeration (or enum) in C


Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read
and maintain.

Important points about enumerations:


➢Definition of an enumeration type:
The general form of enumeration type definition is:
[storage_class_specifier][type_qualifier] enum [tag-name] {enumeration-
list}[identifier=initializer[,…]];

▪ An enumerator is an identifier that can hold an integer value. It is also known


as enumeration constant.
▪ The names of the enumerators in the enumeration list must be unique
▪ values assigned to enumerators in the enumeration list need not be unique
e.g. the enumeration definition enum COLORS {red=2, green=1, yellow=1}; is
perfectly valid.
▪ Each enumeration constant has a scope that begins just after its appearance
in the enumeration list.
▪ enum COLORS {red=2, green=red, yellow=green}; is perfectly valid.

33

// An example program to demonstrate working


// of enum in C
#include<stdio.h>
main()
{
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

enum week day;

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

// Another example program to demonstrate working of enum in C


#include<stdio.h>
main()
{
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
} 0 1 2 3 4 5 6 7 8 9 10 11

In this example, the for loop will run from i = 0 to i = 11,


as initially the value of i is Jan which is 0 and the value of
Dec is 11.

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

Dynamic Memory Allocation in C


using
malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for
programming. One of them includes changing the size of an array.
An array is a collection of items stored at contiguous memory
locations.

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.

This procedure is referred to as Dynamic Memory Allocation


in C. Therefore, C Dynamic Memory Allocation can be defined
as a procedure in which the size of a data structure (like Array)
is changed during the runtime. C provides some functions to
achieve these tasks.

38

19
25-02-2022

There are 4 library functions provided by C defined


under <stdlib.h> header file to facilitate dynamic
memory allocation in C programming.

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

If space is insufficient, allocation fails and returns a


NULL pointer.

41

// Program to calculate the sum of n for(i = 0; i < n; ++i) {


numbers entered by the user scanf("%d", ptr + i);
sum += *(ptr + i);
#include <stdio.h> }
#include <stdlib.h>
printf("Sum = %d", sum);
main() {
int n, i, *ptr, sum = 0; // deallocating the memory
printf("Enter number of elements: "); free(ptr);
scanf("%d", &n);
}
ptr = (int*) malloc(n * sizeof(int));
Enter number of elements: 5
// if memory cannot be allocated Enter elements:
if(ptr == NULL) { 23
printf("Error! memory not allocated."); 65
exit(0); 12
45
}
89
printf("Enter elements: \n"); Sum = 234

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.

ptr = (float*) calloc(25, sizeof(float));


This statement allocates contiguous space in memory for 25
elements each with the size of the float.

43

// Program to calculate the sum


of n numbers entered by the user printf("Enter elements:\n");
#include <stdio.h> for(i = 0; i < n; ++i) {
#include <stdlib.h> scanf("%d", ptr + i);
main() sum += *(ptr + i);
{ }
int n, i, *ptr, sum = 0;
printf("Enter number of printf("Sum = %d", sum);
elements: "); free(ptr);
scanf("%d", &n);
}
ptr = (int*) calloc(n, sizeof(int)); Enter number of elements: 5
if(ptr == NULL) { Enter elements:
45
printf("Error! memory not 21
789
allocated."); 432
exit(0); 54
Sum = 1341
}

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

#include <stdio.h> exit(0);


#include <stdlib.h> }
main() else {
{ // Memory has been successfully allocated
// This pointer will hold the printf("Memory successfully allocated using
// base address of the memory block created malloc.\n");
int *ptr, *ptr1; // Free the memory
int n, i; free(ptr);
// Get the number of elements for the array printf("Malloc Memory successfully freed\n");
printf("Enter number of elements:"); // Memory has been successfully allocated
scanf("%d",&n); printf("\nMemory successfully allocated using
/* Dynamically allocate memory using calloc.\n");
malloc()*/ // Free the memory
ptr = (int*)malloc(n * sizeof(int)); free(ptr1);
/* Dynamically allocate memory using printf("Calloc Memory successfully freed.\n");
calloc() */ }
ptr1 = (int*)calloc(n, sizeof(int)); }
// Check if the memory has been successfully
Enter number of elements:5
// allocated by malloc or not Memory successfully allocated using malloc.
if (ptr == NULL || ptr1 == NULL) { Malloc Memory successfully freed
printf("Memory not allocated.\n");
Memory successfully allocated using calloc.
Calloc Memory successfully freed.

46

23
25-02-2022

❑exit() is a system call which terminates


current process. exit() is not an instruction of
C language.

❑Whereas return() is a C language


instruction/statement and it returns from the
current function (i.e. provides exit status to
calling function and provides control back to
the calling function).

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

Dynamic Memory Allocation Examples using C

/*C program to create memory for int,


char and float variable at run time.*/ printf("Enter character value: ");
scanf(" %c",cvar);
#include <stdio.h>
#include <stdlib.h> printf("Enter float value: ");
scanf("%f",fvar);
main()
{ printf("Inputted value are: %d, %c,
int *ivar; %.2f\n",*ivar,*cvar,*fvar);
char *cvar;
float *fvar; /*free allocated memory*/
free(ivar);
/*allocating memory dynamically*/ free(cvar);
ivar=(int*)malloc(1*sizeof(int)); free(fvar);
cvar=(char*)malloc(1*sizeof(char)); }
fvar=(float*)malloc(1*sizeof(float)); Enter integer value: 4
Enter character value: h
printf("Enter integer value: "); Enter float value: 4.7
scanf("%d",ivar); Inputted value are: 4, h, 4.70

51

Dynamic Memory Allocation Examples using C


/*C program to read and print the student printf("Insufficient Memory, Exiting... \n");
details using structure and Dynamic Memory return 0;
Allocation.*/ }
#include <stdio.h> /*read and print details*/
#include <stdlib.h> printf("Enter name: ");
/*structure declaration*/ gets(pstd->name);
struct student printf("Enter roll number: ");
{ scanf("%d",&pstd->roll);
char name[30]; printf("Enter percentage: ");
int roll; scanf("%f",&pstd->perc);
float perc; printf("Entered details are:\n");
}; printf("Name: %s, Roll Number: %d,
main() Percentage: %.2f\n",pstd->name,
{ struct student *pstd; pstd->roll,pstd->perc);
/*Allocate memory dynamically*/ }
pstd=(struct student*)malloc(1*sizeof(struct
student));
Enter name: Ramesh
if(pstd==NULL) Enter roll number: 23
{ Enter percentage: 76.09
Entered details are:
Name: Ramesh, Roll Number: 23, Percentage: 76.09

52

26
25-02-2022

END
53

27

You might also like