Unit V

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

UNIT V - POINTERS AND FILE MANAGEMENT

Pointer concepts - Pointers & Arrays, Structure concepts - Defining, Declaring, Accessing Member
Variables, Structure within Structure - Union - File Management in C- Dynamic Memory Allocation.

POINTERS
Definition
A pointer is a variable that stores the address of another variable. A pointer represents the
location of a data item in the memory. It is a derived data type used in C Language.
Syntax
datatype *variable_name;
Example1
int *ptr;
ptr = &a;
Here,
ptr  Pointer Variable, it holds the memory address of another variable ‘a’
&a  Address of variable ‘a’, it is stores in pointer variable ‘prt’
Example2
a  Variable
10  Value
2000  Address
Now,
int *p; //Pointer variable
p = &a; //Address of ‘a’ is assigned to pointer
Hence,

p = 2000
*p = 10
Pointer Operator

Operator Operator Name Purpose


* Value at Operator Gives Value stored at Particular address
& Address Operator Gives Address of Variable

In order to create pointer to a variable use “*” operator and to find the address of variable use
“&” operator.

 ‘&’ operator is called as address Operator


 ‘*’ is called as ‘Value at address’ Operator
 ‘Value at address’ Operator gives ‘Value stored at Particular address.
 ‘Value at address’ is also called as ‘Indirection Operator’

Write a C program to print address and value of a variable


#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
int *p;
p=&a;
printf("\nAddress of a is %u",p);
printf("\nValue of a is %d",*p);
getch();
}
Output
Address of a is 65524
Value of a is 10
Pointer Declaration
A pointer is a variable that contain address of another variable
Syntax
datatype *variable_name;
Example
int a=10; //interger
int *p;
p = &a;
float b=15.23; //float
float *p1;
p1 = &b;
char name[10]=”Tamil”; //Characters
char *p2;
p2 = &name;
Initialization of the Pointer variable
The process of assigning the address of a variable to the pointer variable is known as
initialization.
Example
int a=10;
int *ptr = &a; //initialization
Pointer Types
There are various types of pointers used in C Language. They are
a. void pointer
b. Null pointer
c. Pointer-to-pointer
d. Pointer arithmetic / Pointer Expression.
a. void pointer
Pointer that can point to any type of data item is known as void pointer. It is a general
purpose pointer used for pointing to different data types.
Syntax
void *ptr_name
Example
int a=10;
void *ptr;
ptr=&a;
float a=12.6;
void *ptr;
ptr=&a;
char a=’z’;
void *ptr;
ptr=&a;
Here, variable ‘a’ can hold integer or float or character etc.
b. Null pointer
A pointer is said to be a Null pointer, when its right hand side value is zero(0). A Null
pointer can never point a valid data.
Example
int c = 5;
int *a,*b;
a=0; //Null pointer
b = &c;
Here, a  Null pointer
b Valid pointer

c. Pointer-to-pointer
Usually pointer variable stores the address of another variable. Pointer-to-pointer stores
address of another pointer variable.
Example

**p2 =
*p1 = &a ***p3 = &p2
&p1
Variable a p1 p2 p3
Value  10 1000 2000 3000
Address 1000 2000 3000 4000
Here,
*p1  Pointer
**p2, ***p3  Pointer-to-pointer
p1 = 1000
*p1 = 10
p2 = 2000
*p2 = 1000
**p2 = 10
p3 = 3000
*p3 = 2000
**p3 = 1000
***p3 = 10

Write a C program to illustrate pointer-to-pointer concept


#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
int *p1,**p2,***p3;
clrscr();
p1=&a;
p2=&p1;
p3=&p2;
printf("\nValue of a is %d",a);
printf("\nValue of a is %d",*p1);
printf("\nValue of a is %d",**p2);
printf("\nValue of a is %d",***p3);
printf("\n\nAddress of a is %u",&a);
printf("\nAddress of a is %u",p1);
printf("\nAddress of p1 is %u",p2);
printf("\nAddress of p2 is %u",p3);
getch();
}

Output
Value of a is 10
Value of a is 10
Value of a is 10
Value of a is 10
Address of a is 1000
Address of a is 1000
Address of p1 is 2000
Address of p2 is 3000
d. Pointer Arithmetic
Pointer variables can be used in expressions. We can add, subtract the integer using
pointer variables. It is also called as pointer expression.
Example
*c = *a + *b; *c = (*a) + (*b);
*a = *a + 5; or *a = (*a) + 5;
*p = *x * *b; *p = (*x) * (*b);
Write a C program to illustrate pointer arithmetic concept
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
int *pa,*pb,*pc;
clrscr();
printf("\nEnter 2 numbers:");
scanf("%d%d",&a,&b);
pa=&a;
pb=&b;
pc=&c;
*pc=*pa+*pb;
printf("\nSum=%d",*pc);
getch();
}
Output

Enter 2 numbers: 3 5
Sum = 8

Pointer and Arrays


In C Language, there is a strong relationship between pointers and arrays. Most use of
pointers in C is pointer and array. It is notational convenient and increases the program
efficiency.
Declaration
int a[10];
int *pa;

Assignment
pa = &a[0];
Or
pa = a;

pa pa + 1 pa + 2 pa + 3 pa + 4 pa + 5
a
0 1 2 3 4 5
Pointer variable is incremented automatically for further initialization as shown above.
Example

int a[5] = {10, 20, 30, 40, 50};


int *b; //Pointer declaration
b = a; //Initialization of an array to pointer

0 1 2 3 4
A 10 20 30 40 50
4000 4002 4004 4006 4008
When pointer variable is incremented by 1, related base address will be incremented by (address
+ 2) because above declared type in an “integer”.

Write a C program to illustrate pointer and array concept.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={10,20,30,40,50};
int i,*ptr[5]; //Pointer & array declaration
clrscr();
for(i=0;i<5;i++)
{
ptr[i]=&a[i]; //Initialization
}
for(i=0;i<5;i++)
{
printf("\nValue of a[%d] = %d",i,*ptr[i]);
}
getch();
}

Output
Value of a[0] = 10
Value of a[1] = 20
Value of a[2] = 30
Value of a[3] = 40
Value of a[4] = 50

Pointer and Function


Pointer can be used as arguments in function. Pointer when passed within the function, it
is called as Call by reference or Pass by reference.
Example
swap(&a, &b);
add(&a, &b);
subtract(&x, &y);
etc.,

Write a C program to perform arithmetic operations of two numbers using pointer and
functions
#include<stdio.h>
#include<conio.h>
void add(int *,int *);
void sub(int *,int *);
void mul(int *,int *);
void main()
{
int a,b,choice;
clrscr();
printf("\nEnter 2 numbers:");
scanf("%d%d",&a,&b);
printf("1.Addition\n2.Subtraction\n3.Multiplication\n");
printf("Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
add(&a,&b);
break;
case 2:
sub(&a,&b);
break;
case 3:
mul(&a,&b);
break;
default:
printf("Enter correct choice");
break;
}
getch();
}
void add(int *a,int *b)
{
int *add;
*add=*a+*b;
printf("\nSum=%d",*add);
}
void sub(int *a,int *b)
{
int *sub;
*sub=*a-*b;
printf("\nSubtraction=%d",*sub);
}
void mul(int *a,int *b)
{
int *mul;
*mul=*a**b;
printf("\nMultiplication=%d",*mul);
}

Output
Enter 2 numbers: 5 6
1.Addition
2.Subtraction
3.Multiplication
Enter your choice: 1
Sum=11
Enter 2 numbers: 5 6
Enter your choice: 2
Subtraction=-1
Enter 2 numbers: 5 6
Enter your choice: 3
Multiplication=30

Advantage of Pointer
1. Pointers are most efficient in handling arrays and functions.
2. Pointer allows dynamic memory management.
3. A pointer reduces length and complexity of program.
4. Pointer increases the execution speed and reduces the program execution time.
5. Pointer provide an efficient tool for manipulation dynamic data structure such as stack,
queue, linked lists, structures etc.,

STRUCTURE
An array is collection of similar data type. But user cannot fulfill all needs with same data
type. For example, if users want to collect student data base, he/she need to collect following
data roll number (integer), name (character), mark (float) etc. In such situation user cannot use
array data type alone. Hence collection of different data type is needed.
Structure is a derived data type. Structure is used to collect dissimilar data type. It is used
to collect different data type under common name. Structure is declared using ‘struct’ keyword.
Syntax
struct structure_name
{
structure members;
......
}object;

Here,
struct  keyword
object  it is used to access the members of the structure.

Example
struct student
{
int roll;
char name[20];
float mark;
}stu;
Structures members cannot be accessed directly. It can be accessed using its object with dot ( . )
operator as follows.
stu.roll;
stu.name;
stu.mark;
Defining a Structure
A Structure can be defined as follows
struct identifier
{
datatype member 1;
datatype member 2;
......
......
datatype member n;
};
where, struct is a keyword, identifier is a name that identifies structures. Member 1,
Member 2 ..... Members n are individual member declarations.
Declaring a Structure
A structure declaration is similar to the declaration of variables of any other data type. It
includes the following statements
1. Keyword “struct”
2. Structure name
3. List of members separated by semicolon
4. Objects to access members of structure
5. Terminating symbol

Example
struct book
{
int book_id;
char title[20];
char author[20];
float price;
}b1,b2;
where, struct is a keyword, book is a name that identifies structures. book_id, title, author
and price are individual member of structure. b1 & b2 are objects to access members of structure.

Accessing Structure members


The members of structures cannot be accessed like normal variable in C. Structures
members requires “object” to access it. Syntax for accessing structure members
Syntax
object . structure_member;

Example
b1.book_id; b2.book_id;
b1.title; b2.title;
b1.author; b2.author;
b1.price b2.price

Object can be created in two methods,


Method 1 Method 2
An object can be created in An object can be created inside the
structure declaration main( ) function
struct employee
struct employee
{
{
int id;
int id;
char name[20];
char name[20];
float salary;
float salary;
};
}emp;
void main( )
void main( )
{
{
struct employee emp;//object
.....
.....
emp.id;
emp.id;
emp.salary;
emp.salary;
.....
.....
}
}

Memory allocation of Structure members


The members of structures contain unique memory allocation. Each and every individual
members of structure is allocated in its own memory.
Example
struct student
{
int roll;
char name[5];
float mark;
}stu;

Memory allocation of above example is given below,


roll 2 Bytes

name 5 Bytes

float 4 Bytes

Rules for declaring a structure


1. Structure must end with a semicolon.
2. Usually structure appears at the top of the source program.
3. Each structure element must be terminated.
4. Structure members are accessed using its object with dot operator.

Initialization of Structure members


The members of structures can be initiated like a normal variable as follows

Example1:
struct student
{
int roll;
char name[5];
float mark;
}stu={5, Tamil, 97.5};
Example2
struct book
{
int book_id;
char title[20];
char author[20];
float price;
};
struct book b1={100, “Computer Programming”, “Tamil”, 350.00};
struct book b1={210, “Computer Practice Lab”, “Selva”, 300.00};

Sample C Program using Structure


1. Write a C program to display one student detail using structure
#include<stdio.h>
#include<conio.h>
struct student
{
int roll;
char name[20];
float mark;
}stu;
void main()
{
clrscr();
printf("\nEnter student details:");
printf("\nRoll Number:");
scanf("%d",&stu.roll);
printf("\nName:");
scanf("%s",stu.name);
printf("\nMark:");
scanf("%f",&stu.mark);
printf("\nStudent details are:");
printf("\nRoll number=%d \nName=%s \nMark=%f", stu.roll, stu.name, stu.mark);
getch();
}

Output
Enter student details
Roll Number : 6 Name : Tamil Mark : 97.5

Student details are:


Roll Number = 6 Name = Tamil Mark = 97.5
Nested Structure
A structure within another structure is called as nested structure. Elements of nested
structure are accessed using dot operator.
Example
struct date
{
int day;
char month[5];
int year;
};
struct employee
{
int id;
char name[20];
float salary;
struct date doj; // structure declaration within another structure
};
void main( )
{
struct employee emp; //object creation
.....
.....
emp.id;
emp.name;
emp.salary;

emp.doj.day;
emp.doj.month;
emp.doj.year

Write a C program to display employee detail using structure within structure


#include<stdio.h>
#include<conio.h>
struct date
{
int day;
char month[10];
int year;
};
struct employee
{
int id;
char name[20];
struct date doj;
};
void main()
{
struct employee emp;
clrscr();
printf("\nEnter Employee details:");
printf("\nID:");
scanf("%d",&emp.id);
printf("\nName:");
scanf("%s",emp.name);
printf("\nDate of Joining:");
scanf("%d%s%d",&emp.doj.day,emp.doj.month,&emp.doj.year);
printf("\nEmplyee details are:\n");
printf("ID\tName\tDate of joining\n");
printf("%d\t%s\t%d%s%d",emp.id,emp.name,

emp.doj.day,emp.doj.month,emp.doj.year);
getch();
}

Output
Enter Employee details
ID: 12
Name: Tamil
Date of Joining: 27 June 2007
Employee details are:
ID Name Date of joining
12 Tamil 27 June 2007

Union:
It is a special data type available in C that allows storing different data types in the same
memory location. You can define a union with many members, but only one member can contain
a value at any given time. Unions provide an efficient way of using the same memory location
for multiple purposes.

Syntax:
union [union name]
{
member definition;
member definition;
...
member definition;
}union variable declaration;

union Data {
int i;
float f;
char str[20];
} data;

#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}

Output:
Memory size occupied by data : 20

FILES

File is defined as a set of records that can be accessed through various file functions. In
order to store information permanently and retrieve it we need to use files. To use files we have
to learn about how to write information to a file and how to read information from a file.
Basically there are two types of files in the C:
 Sequential files: The data will be stored or read sequentially.
 Random access files: Data will be accessed and processed randomly.
File operations
i. File create and file open
ii. File read and File write
iii. File close
iv. File positioning functions
v. File error handling functions
i. File create and File open:
A file must be opened before performing any input or output operations.
Syntax

FILE *fp; File pointer

Keyword

fp=fopen(“file-name”, “file modes”);

The various file modes are


Modes Operation Description
It opens the existing file for reading purpose only. If the file does
“r” Read only
not exist, fopen fails.
It opens the file for writing purpose only. If the file does not
“w” Write only exist, a new file is created. If the file exists its contents are
destroyed.
It opens the file to write the contents at the end of file. If the file
“a” Append
does not exist a new file is created.
It opens the existing file both for reading and writing. If the file
“r+” Read and Write
does not exist, fopen fails.
It opens a file both for reading and writing. If a file exists its
“w+” Read and Write contents are destroyed. If the file does not exist, a new file is
created.
Read, Write It opens to read and write at the end of existing file or create a
“a+”
and Append new file.
Example

FILE *fp1, *fp2;


fp1=fopen(“Inputfile”, “r”);
fp2=fopen(“Outputfile”, “w”);

ii. File Read and Write


Files can be read using following file functions.
 Formatted Input/Output file functions
 Unformatted Input/Output file functions
 Formatted Input file functions
fscanf() – Read a number of values from a file.
Syntax:

fscanf(fp, “control string”, &var 1, &var 2, ………….., &var N);

Example:

fscanf(fp1, “%d%s%f”, &sno, name, &mark);

 Formatted Output file function


fprintf()  Writes a number of values to a file
Syntax

fprintf(fp, “control string”, &var 1, &var 2, ………….., &var N);

Example

fprintf(fp2, “%d%s%f”, sno, name, mark);

Example for Formatted Input/Output file functions (Sequential Access)

#include<stdio.h>
#include<conio.h>
void main()
{
int rno;
char name[15] ;
FILE *fp1, *fp2;
fp1=fopen(“input.txt”, “r”);
fp2=fopen(“output.txt”, “w”);
while(!feof(fp1))
{
fscanf(fp1, “%d%s”, &rno, name);
fprintf(fp1, “%d\t%s\n”, &rno, name);
}
fclose(fp1);
fclose(fp2);
}
OUTPUT
Input File (Input.txt)
1001 kavi
1002 tamil
1003 sathya
Output File (Output.txt)
1001 kavi
1002 tamil
1003 sathya

 Unformatted Input file functions


Unformatted Input file functions
i. fgetc()
ii. getw()
iii.fgets()
i. fgetc()  Reads a single character from file.
Syntax:
Var1 = fgetc(fp);
Example:
a = fgetc(fp1);

ii. getw()  Reads the integer value from the file.


Syntax:
Var = getw(fptr);
Example:
a = getw(fp1);

iii. fgets()  Used to read a string from a file.


Syntax:
fgets(str, length, fptr);
 str  The read string is to be stored.
 length  Maximum length of the string.
 fptr  File pointer.
Example:
fgets(str1, 20, fp1);

 Unformatted Output file functions


i. fputc()
ii. putw()
iii. fputs()
i. fputc() – Writes a single character to file.
Syntax:
fputc(var, fp);
Example:
fputc(ch, fp2);
ii. putw() – Writes an integer value into the file.
Syntax:
putw(Num, fptr);
Example:
putw(Num, fp2);

iii. fputs() – Writes the string to the file.


Syntax:
fputs(str, fptr);
Example:
fputs(str2, fp2);

Example for Unformatted Input/Output file functions ( Sequential Access)


#include<stdio.h>
#include<conio.h>
void main()
{
int rno;
char name[15] ;
char grade;
FILE *fp1, *fp2;
fp1=fopen(“input.txt”, “r”);
fp2=fopen(“output.txt”, “w”);
while(!feof(fp1))
{
rno=getw(fp1);
grade=fgetc(fp1);
fgets(name, 10, fp1);
putw(rno, fp2);
fputc(grade, fp2);
fputs(name, fp2);
}
fclose(fp1);
fclose(fp2);
}
OUTPUT:
input.txt
1001 Kavi S
1002 Tamil A
1003 Sathya S
1004 Balaji A
output.txt
1001 Kavi S
1002 Tamil A
1003 Sathya S
1004 Balaji A
iii. File Close
After completing read and write operations, the file is closed using fclose().
Syntax:
fclose(fptr);
Example:
fclose(fp1);

iv. File Positioning Functions


a. fseek()  Moves the file position to a specific location in a file.
Syntax:

fseek(fptr, offset, position);


Position takes three values (0,1,2)
 If position is assigned as 0, then the file pointer moves from the beginning of the
file.
 If position is assigned as 1, then the file pointer moves from the current location
of the file.
 If position is assigned as 2, then the file pointer moves to the end of the file.
Example:

fseek(fp1, 10, 1)  The fpointer moves 10 bytes from the current position.

b. ftell()  It is used to get the current position of the file pointer.


Syntax:

var = ftell(fptr);

Example:
n = ftell(fp1);

c. rewind() It is used to move the file pointer to the beginning of the file.
Syntax:

rewind(fp)

Example:

rewind(fp1)

Example Program for Random Access in file

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1;
clrscr();
fp1=fopen("inputfile.txt","r");
if(fp1!=NULL)
{
printf("\nThe file pointer is at location:%d",ftell(fp1));
fseek(fp1,13,0);
printf("\nThe file pointer is at location:%d",ftell(fp1));
fseek(fp1,4,1);
printf("\nThe file pointer is at location:%d",ftell(fp1));
fseek(fp1,0,2);
printf("\nThe file pointer is at location:%d",ftell(fp1));
fseek(fp1,-10,2);
printf("\nThe file pointer is at location:%d",ftell(fp1));
rewind(fp1);
printf("\nThe file pointer is at location:%d",ftell(fp1));
}
getch();
}
Input File
Random File Access
OUTPUT
The file pointer is at location: 0
The file pointer is at location: 13
The file pointer is at location: 17
The file pointer is at location: 18
The file pointer is at location: 8
The file pointer is at location: 0

v. File Error Handling Functions


 clearerr( )  Clears errors.
 feof( )  It is used to determine whether the file pointer is at the end of the file
or not.
Syntax:
feof(FILE *fptr);
 ferror( )  It is used to check whether any error has occurred, while performing
read and write operation.
Syntax:
ferror(fptr);
File Manipulations
The various file manipulation functions are
FILE *fp File create
fopen() File open
fscanf() Read values
fprintf() Write values
fgetc() Read single character
fgets() Read string
fputc() Reads single character
putw() Write integer value
fputs() Writes string
fclose() File close
fseek() Move file position to specific location
ftell() Get current position of file pointer
rewind() Move file pointer to beginning file
fgetpos() Indicate file position
fsetpos() Move file position indicator to specific location
clearer() Clears error
feof() Determine end position
ferror() Cheak error while perform read and write
fread() Take items in binary mode
fwrite() write plain-text

Sequential access file

 In sequential file access file contents are accessed sequential order i.e., one after another.
 In sequential file, data are kept sequential. For example if user wants to access the forty
fourth record, first forty three records should be read sequentially to reach the forty fourth
record.
 It takes more time
 Example: Tape Drive, Magnetic Tape

Features

 Records are written in the order in which they are entered.


 Records are read and written sequentially
 Records have the same size and same field format.
 Used for report generation

Advantage

 Simple and easy to handle.


 No extra overhead involved.
 Well suited for batch-oriented applications.

Disadvantage

 Records can be read only sequentially, if user want to access 50 th record, then first 49
records must be read.
 Sequential file access does not support update operation.
 Cannot be used for interactive applications.
Random Access File

 In the random access file, the data can be accessed and processed randomly i.e in this
case the forty fourth record can be accessed directly. It takes less time than the sequential
file.

 C support following functions for Random Access File processing.


o fseek()
o ftell()
o rewind()

Dynamic Memory Allocation


The concept of dynamic memory allocation in c language enables the C programmer to
allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions
of stdlib.h header file.
 malloc() - allocates single block of requested memory.
 calloc() - allocates multiple block of requested memory.
 realloc() - reallocates the memory occupied by malloc() or calloc() functions.
 free() - frees the dynamically allocated memory.

Difference between static and dynamic memory allocation


static memory allocation dynamic memory allocation
Memory is allocated at compile time. Memory is allocated at run time.
Memory can't be increased while Memory can be increased while
executing program. executing program.
Used in array. Used in linked list.

1. malloc()
 The name malloc stands for "memory allocation".
 The function malloc() reserves a block of memory of specified size and return a pointer
of type void which can be casted into pointer of any form.
 The malloc() function allocates single block of requested memory.
 It doesn't initialize memory at execution time, so it has garbage value initially.
 It returns NULL if memory is not sufficient.
Syntax
ptr=(cast-type*)malloc(byte-size)
Example
ptr = (int*) malloc(10 * sizeof(int));
This statement will allocate 20 bytes according to size of int (2 bytes) and the pointer
points to the address of first byte of memory.
Program
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
getch();
}
OUTPUT
Enter number of elements: 3
Enter elements of array: 1 2 4
Sum=7

2. calloc()

 The name calloc stands for "contiguous allocation".


 The only difference between malloc() and calloc() is that, malloc() allocates single block
of memory whereas calloc() allocates multiple blocks of memory each of same size and
sets all bytes to zero.
 The calloc() function allocates multiple block of requested memory.
 It initially initialize all bytes to zero.
 It returns NULL if memory is not sufficient.
Syntax
ptr=(cast-type*)calloc(number, byte-size)
Example
ptr = (int*) calloc(10, sizeof(int));
ptr = (int*) calloc(10, 10*sizeof(int));
This statement allocates contiguous space in memory for an array of 10 elements each of
size of int, i.e, 2 bytes. 10 blocks of memory 10*2 bytes will be allocated. Totally 10*20
= 200 bytes will be allocated.
Program

#include<conio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
getch();
}
OUTPUT
Enter number of elements: 3
Enter elements of array: 1 2 4
Sum=7

3. realloc()

If memory is not sufficient for malloc() or calloc(), user can reallocate the memory by
realloc() function. In short, it changes the memory size.

Syntax
ptr=realloc(ptr, new-size)

4. free()

The memory occupied by malloc() or calloc() functions must be released by calling free()
function. Otherwise, it will consume memory until program exit.

Syntax

free(ptr)
Difference between malloc() and calloc() functions in C:

malloc() calloc()
It allocates multiple blocks of requested
It allocates only single block of requested memory
memory
int *ptr;Ptr = calloc( 20, 20 * sizeof(int) );
int *ptr;ptr = malloc( 20 * sizeof(int) );
For the above, 20 blocks of memory will be
For the above, 20*4 bytes of memory only allocated
created and each contains 20*4 bytes of
in one block.
memory.
Total = 80 bytes
Total = 1600 bytes
malloc () doesn’t initializes the allocated memory. calloc () initializes the allocated memory to
It contains garbage values zero