0% found this document useful (0 votes)
2 views63 pages

pointer in c

c notes

Uploaded by

pravesh koirala
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)
2 views63 pages

pointer in c

c notes

Uploaded by

pravesh koirala
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/ 63

A pointer is a special type of variable that holds

the location of another variable.


 It is really a powerful variable which is used to
directly deal with memory of computer.
 A pointer is denoted by ‘*’ and has to be declared
in the similar way as we declare other variables.
 Example:
float x; // x is a normal floating point variable
float *m; // a pointer that points an integer data

3/17/2021 7:45:48 AM 2
 It allows us to pass variables, arrays, functions, string
and structures as function arguments.
 It provides a way to return multiple values from a
function.
 Pointer assigns the memory space and also releases it
which makes the best use of the available memory
(dynamic memory allocation).
 The execution time is faster because data
manipulation is done directly inside memory.
 Pointer is closed to array so it is efficient for solving
array and string related problems.
 Pointer is closed to hardware so it is very efficient
for solving hardware interfacing problems.
 It allows to establish links between data elements for
complex data structures such as linked list, stacks,
queues, trees and graphs.
3/17/2021 7:45:48 AM 3
 There are two pointer operators: ‘&’ operator and
‘*’ operator.
 The ‘&’ operator is called ‘address of’ operator
which is unary operator that returns the memory
address of its operand.
 In other words, the pointer operator ‘&’ is an
operator that returns the address of the variable
following it.
 For example:
n = &x;
where ‘n’ receives the address of the variable ‘x’.
It has nothing to do with the value of ‘x’.

3/17/2021 7:45:48 AM 4
 The ‘*’ operator is called ‘value at address’ operator
which gives the value stored at the specified address.
 For example: address of v value of v
pv v
Fig. Relationship between pv and v
(where pv = &v and v = *pv)
 The data item represented by v (i.e. the data item
stored in v’s memory cells) can be accessed by the
expression *pv, where * is a unary operator, called the
‘indirection operator’, that operates only on a pointer
variable.
 Therefore, *pv and v both represent the same data
item. Furthermore, if we write pv=&v and u=*pv, then
‘u’ and ‘v’ will both represent the same value; i.e.
the value of ‘v’ will indirectly be assigned to ‘u’

3/17/2021 7:45:48 AM 5
 Pointers are built on the three underlying concepts as illustrated
below:

Pointer Pointer Pointer


Constants Values Variables

Pointers

 Memory addresses within a computer are called pointer


constants. We cannot change them; we can only use them to
store data values.
 We cannot save the value of a memory address directly. We can
only obtain the value through the variable stored there using ‘&’
and that is called pointer value. The pointer value (i.e. the
address of a variable) may change from one run of the program
to another.
 The variable that contains a pointer value is called a pointer
variable.
3/17/2021 7:45:48 AM 6
A program to display the address of a
variable along with its value.

#include<stdio.h>
void main()
{ Output:
char a; A is stored at address 65525.
125 is stored at address 65522.
int x;
10.250000 is stored at address 65518.
float p,q; 18.760000 is stored at address 65514.
a = ‘A’;
x = 125;
p = 10.25, q = 18.76;
printf(“%c is stored at address %u.\n”,a,&a);
printf(“%d is stored at address %u.\n”,x,&x);
printf(“%f is stored at address %u.\n”,p,&p);
printf(“%f is stored at address %u.\n”,q,&q);
}
3/17/2021 7:45:48 AM 7
 A program that illustrates the relationship between
two integer variables, their corresponding addresses
and their associated pointers.

#include<stdio.h>
void main()
{ int u=3; Output:
int v; u=3 &u=fff4 pu=fff4 *pu=3
int *pu; u=3 &v=fff2 pv=fff2 *pv=3
int *pv;
pu = &u;
v = *pu;
pv = &v;
printf(“\nu=%d &u=%x pu=%x *pu=%d”,u,&u,pu,*pu);
printf(“\nv=%d &v=%x pv=%x *pv=%d”,v,&v,pv,*pv);
}
3/17/2021 7:45:48 AM 8
 Therelationship between pu and u, and pv
and v are shown in the fig. given below:
Address ?? Address ‘fff4’
fff4 3

pu u

Address ?? Address ‘fff2’


fff2 3

pv v

3/17/2021 7:45:48 AM 9
#include<stdio.h>
void main()
{
int u1,u2;
int v = 3; Output:
int *pv; u1 = 16 u2 = 16
u1 = 2 * (v + 5);
pv = &v;
u2 = 2 * (*pv + 5);
printf(“\nu1=%d u2=%d”, u1,u2);
}

3/17/2021 7:45:48 AM 10
#include<stdio.h>
void main() Output:
{ *pv = 3 v=3
int v = 3; *pv = 0 v=0
int *pv;
pv = &v;
printf(“\n *pv=%d \t v=%d”,*pv,v );
*pv = 0;
printf(“\n *pv=%d \t v=%d”,*pv,v );
}

3/17/2021 7:45:48 AM 11
 We can declare a pointer variable like ordinary
variables by putting the * operator before
variable.
Syntax
data_type *pt_var;
 This tells the compiler three things about the
variable ‘pt_var’.
 The variable ‘pt_var’ is a pointer variable.
 ‘pt_var’ needs a memory location
 ‘pt_var’ points to a variable of type ‘data_type’

 Forexample: int *p; declares the variable


‘p’ as a pointer variable that points to an integer
data type.
3/17/2021 7:45:48 AM 12
 Pointer variables are declared similarly as
normal variables except for the addition of the
unary operator ‘*’.
 This symbol ‘*’ can appear anywhere between
the type name and the pointer variable name as
shown below:
1. int* p;
2. int *p;
3. int * p;

3/17/2021 7:45:48 AM 13
 The process of assigning the address of a
variable to a pointer variable is called
pointer initialization.
 All uninitialized pointers will have some
unknown values that will be interpreted as
memory addresses. They may not be valid
addresses or they may point to some values
that are wrong.
 Once a pointer variable has been declared
we can use the assignment operator to
initialize the variable. For example:
int x;
int *y; //declaration
y = &x; //initialization
3/17/2021 7:45:48 AM 14
 We can also combine the initialization with the
declaration i.e. int *y = &x;.
 The only requirement here is that the variable x
must be declared before the initialization takes
place.
 We must ensure that the pointer variables always
point to the corresponding type of data. For
example:
float a, b;
int x, *p;
p = &a; //wrong
b = *p;

3/17/2021 7:45:48 AM 15
 Itis also possible to combine the declaration of
data variable, the declaration of pointer
variable and the initialization of pointer
variable in one step. For example,
int x, *p = &x; //three in one
 The statement int *p = &x, x; is invalid.

3/17/2021 7:45:48 AM 16
 We can have pointer to pointer, just as we have
pointer to integer.
 Pointer to pointer offers flexibility in handling
arrays, passing pointer variables to functions etc.
 It is possible to make a pointer to point to another
pointer thus creating a chain of pointers as shown
below:
address2 address1 value

p2 p1 variable
 Here, the pointer variable p2 contains the address
of the pointer variable p1, which points to the
location that contains the desired value. This is
known as ‘multiple indirection’.
3/17/2021 7:45:48 AM 17
 Syntax:
data_type **ptr_to_ptr;
Where ptr_to_ptr is a pointer to a pointer
pointing to a data value of the type
‘data_type’.
 A variable that is pointer to pointer must be
declared using additional indirection
operator symbols in front of the name as
int **p2;
 This declaration tells the compiler that
‘p2’ is a pointer to a pointer of ‘int’ type.

3/17/2021 7:45:48 AM 18
void main()
{
int x, *p1, **p2;
x = 100; Output
p1 = &x; 100

p2 = &p1
printf (“%d”, **p2);
}

3/17/2021 7:45:48 AM 19
 Pointer variables can be used in expression like
ordinary variables. For example, if p1 and p2
are properly declared and initialized pointers
then the following statements are valid.
y=*p1+*p2; // or (*p1) * (*p2)
sum=sum+*p1;
z=5*-*p2/ *p1 //or (5*(-(*p2)))/(*p1)
*p2=*p2+10;
 C allows us to add integers to or subtract
integers from pointers, as well as to subtract
one pointer from another. p1+2, p2-6, p1-p2
are all allowed.
3/17/2021 7:45:48 AM 20
 If p1 and p2 are both pointers to the same array ,
then p2-p1 gives the number of elements between
p1 and p2.
 We may also use short-hand operators with the
pointers as p1++; --p2; sum+=*p2; etc.
 Pointers can also be compared using the relational
operators as p1>p2,p1==p2,p1!=p2 etc.
 Any comparison of pointers that refer to separate
and unrelated variables makes no sense.
 We may not use pointers in division or
multiplication. For eg. expression such as p1/p2 or
p1*p2 or p1/3 are not allowed.
 Similarly, two pointers cannot be added i.e. p1+p2
is illegal.
3/17/2021 7:45:48 AM 21
 As with ordinary variables, we may use a pointer
on the right hand side of an assignment operator
to assign its value to another pointer. For eg.
int x,y;
int *p1, *p2;
1. p1=&x;
The memory address of variable x is assigned to the pointer variable p1.

2. y=*p1
The value at the address contained in pointer variable p1 is assigned to
the variable y, not the memory address.
3. p1=&x; p2=p1
The address of the p1 is assigned to the p2. The contents of both p1
and p2 will be the same as these two pointer variables hold the same
address.

3/17/2021 7:45:48 AM 22
Some invalid pointer declaration:
1. int x; Error:
int ptr; Pointer declaration must be
ptr=&x; preceded by *

2. float y Error:
While assigning variable to
float *ptr;
the pointer variable, the
ptr=y;
address operator(&) must
be used along with the
variable y.
3/17/2021 7:45:48 AM 23
#include<stdio.h>
void main() Output:
{
Address of a =….
int a=6;
int *p; Address of a =….
p=&a; Address of p=….
printf(“Address of a=%u\n”,&a); Value of p = ….
printf(“Address of a=%u\n”,p); Value of a = 6
printf(“Address of p=%u”,&p); Value of a = 6
printf(“Value of p=%u”,p);
printf(“Value of a=%d”,*(&a));
printf(“Value of a=%d”,*p);
}

3/17/2021 7:45:48 AM 24
C supports four arithmetic operations that
can be used with pointers such as addition,
subtraction, increment and decrement.
 Each time a pointer is incremented, it points
to the location of the next element of its
base type.
 Each time a pointer is decremented, it points
to the location of the previous element of its
base type.
 When applied to character pointers, this will
appear as normal arithmetic because
characters always occupy one byte.
 All other pointers increases or decreases by
the length of the data type they point to.
3/17/2021 7:45:48 AM 25
 We may add or subtract integer to or from
pointer.
 The expression ptr=ptr+3; makes pointer
variable ‘ptr’ point to the 3rd element pf
ptr’s type beyond the one it currently points
to.

3/17/2021 7:45:48 AM 26
Output:
#include<stdio.h>
void main()
{
Output:
Address of a = 65524
int a=12,b=4,*p1,*p2,x,y,z;
p1=&a; Address of a = 65522
p2=&b;
x=*p1**p2-6; a=12, b=4
y=4*-*p2/ *p1+10;
printf(“Address of a=%u\n”,p1); x=42, y=9
printf(“Address of b=%u\n”,p2);
printf(“a=%d,\tb=%d\n”,a,b); a=2, b=7
printf(“x=%d,\ty=%d\n”,x,y);
*p2=*p2+3; z=8
*p1=*p2-5;
z=*p1**p2-6;
printf(“a=%d,\tb=%d\n”,a,b);
printf(“z=%d\n”,z);
}

3/17/2021 7:45:48 AM 27
#include<stdio.h>
void main()
{
int a=12,*p1;
float b=10.6, *p2;
char c=‘z’, *p3;
p1=&a;
p2=&b;
p3=&c;
printf(“Address of a=%u\n”,p1);
printf(“Address of b=%u\n”,p2);
printf(“Address of c=%u\n”,p3);
p1++; p2++; p3++;
printf(“Address of a after increment=%u\n”,p1);
printf(“Address of b after increment =%u\n”,p2);
printf(“Address of c after increment =%u\n”,p3);
}
3/17/2021 7:45:48 AM 28
#include<stdio.h>
void main()
{
int x=15,y,z;
int *p1,*p2;
p1=&x;
p2=p1+6;
y=*p1+1;
z=++*p1;
printf(“Value of x=%d”,*p1);
printf(“Address in p1=%u”,p1);
printf(“Address in p2=%u”,p2);
printf(“The value of y=%d”,y);
printf(“The value of z=%d”,z);
printf(“The value of x after increment=%d”,*p1);
}
3/17/2021 7:45:48 AM 29
 When we increment a pointer, its value is
incremented by the ‘length’ of the data type
that it points to. This length is called the
scale factor.
 An expression like p1++ will cause the
pointer p1 to point to the next value of its
type.
 For example, if p1 is an integer pointer with
an initial value, say 1234, then after the
operation p1++, the value of p1 will be 1236,
and not 1235.

3/17/2021 7:45:48 AM 30
A pointer variable can be assigned the
address of another variable.
 A pointer variable can be assigned the values
of another pointer variable.
 A pointer variable can be initialized with
NULL or zero value.
 A pointer variable can be pre-fixed or post-
fixed with increment or decrement
operators.
 An integer value may be added or subtracted
from a pointer variable.

3/17/2021 7:45:48 AM 31
 When two pointers point to the same array,
one pointer variable can be subtracted from
another.
 When two pointers point to the objects of
the same data types, they can be compared
using relational operators.
 A pointer variable cannot be multiplied by a
constant.
 Two pointer variables cannot be added.
 A value cannot be assigned to an arbitrary
address(i.e. &x=10; is illegal).
3/17/2021 7:45:48 AM 32
 Pointers can be passed into a function as arguments.
 Arguments can generally be passed into functions in
two ways:
a. Call by Value
b. Call by Reference
Call by Value:
 In this method, the value of each of the actual
arguments in the calling function is copied into
corresponding formal arguments of the called
function.
 With this method, the changes made to the formal
arguments in the called function have no effect on
the value of actual arguments in the calling function.

3/17/2021 7:45:48 AM 33
#include<stdio.h>
void swap(int a, int b);
void main()
{
int a=10;
int b=20;
printf(“Before swapping: a=%d\tb=%d", a, b);
swap(a,b); //call by values
printf("After swapping: a=%d\tb=%d", a, b);
}
void swap(int a, int b)
{
int t; Output:
t=a; Before swapping: a=10 b=20
a=b; After swapping: a=20 b=10
b=t;
}

3/17/2021 7:45:49 AM 34
 In call by reference, the address of the
variable is passed. The contents of that
address can be accessed freely, either within
the function or within the calling routine.
 Moreover any change that is made to the
data item (that is to the contents of the
address) will be recognized in both the
function and the calling routine.
 Thus the use of a pointer as a function
argument permits the corresponding data
item to be altered globally from within the
function.

3/17/2021 7:45:49 AM 35
#include<stdio.h>
void swap(int *a, int *b);
void main()
{
int a=10;
int b=20;
printf(“Before swapping: a=%d\tb=%d", a, b);
swap(&a,&b); //call by reference
printf("After swapping a=%d b=%d", a, b);
}
void swap(int *a, int *b)
{
int t;
t=*a; Output:
*a=*b; Before swapping: a=10 b=20
*b=t; After swapping: a=20 b=10
}

3/17/2021 7:45:49 AM 36
 Its good practice to assign NULL value to a
pointer if you don’t have exact address to be
assigned. This is done at the time of pointer
variable declaration.
 A pointer that is assigned NULL is called a null
pointer. The NULL pointer is a constant with a
value of zero defined in several standard
libraries.
 Example
Output:
#include<stdio.h> The value of ptr= 0
void main()
{ int *ptr = NULL;
printf(“The value of ptr=%x”,ptr);
}
3/17/2021 7:45:49 AM 37
 The void pointer is a generic pointer used to
specify a pointer whose base type is unknown.
 It allows a function to specify a parameter that
is capable of receiving any type of pointer
argument without reporting a type mismatch.
 It is declared using ‘void’ keyword and *
operator.
 Pointers to ‘void’ cannot be dereferenced like
other variables by using, the indirection
operator *.
 Prior to dereferencing a pointer to ‘void’, it
must be suitably typecast to the required data
type.

3/17/2021 7:45:49 AM 38
 Example:
#include<stdio.h>
void main()
Output:
{ x = 50
void *ptr; y = 123.456000

int x=50;
float y=123.456;
ptr = &x;
printf(“x=%d\n”,*(int *)ptr); //*((int *)ptr)
ptr = &y;
printf(“y=%f”,*(float *)ptr);//*((float *)ptr)
}

3/17/2021 7:45:49 AM 39
 An array name by itself is an address or pointer.
 A pointer variable can take different addresses as
values where as an array name is an address or
pointer that is fixed.
 A single dimensional array a[i] is equivalent to *(a + i).
For example: a[4] and *(a+4) refer the same element
of the array a. Thus a[i] or *(a + i) or i[a] can be used
as equivalent.
 Similarly, a two dimensional array a[i][j] is equivalent
to *(*(x + i)+j). For example: a[2][3] and *(*(a + 2)+3)
refer the same element of the array a.
 There is a very close relationship between array and
pointer. As we have already seen the name of an array
is actually the address of the array. So it is essentially
a constant pointer.

3/17/2021 7:45:49 AM 40
#include<stdio.h>
void main()
{
int a[]={1,2,3,4,5};
int i, *ptr;
ptr=&a[0];
printf("a[i]\t &a[i]\t *ptr\t ptr+i\t *(a+i)\t a[i]\t i[a]\n");
for(i=0;i<5;i++)
{
printf("%d\t %p\t %d\t %p\t %d\t %d\t %d\n",a[i],&a[i],
*ptr, ptr+i,*(a+i),a[i],i[a]);
}
}

3/17/2021 7:45:49 AM 41
a[i] &a[i] *ptr ptr+i *(a+i) a[i] i[a]
1 FFEC 1 FFEC 1 1 1
2 FFEE 1 FFEE 2 2 2
3 FFF0 1 FFF0 3 3 3
4 FFF2 1 FFF2 4 4 4
5 FFF4 1 FFF4 5 5 5

3/17/2021 7:45:49 AM 42
#include<stdio.h>
void main()
Output:
{
int a[2][3]={1,2,3,4,5,6}; 1 2 3
int i, j; 4 5 6
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf(“%d\t”,*(*(a+i)+j));
printf(“\n”);
}
}

3/17/2021 7:45:49 AM 43
 Since strings are character arrays, pointers to
strings are treated in a way similar to
pointers to arrays of the other data types.
 The name of the character array (string)
points to the base address of the string (i.e.
the first character of the string).
 The expression (arrayname+i) points to the
ith character in the string.
 The expression (arrayname), &arrayname[0]
and &0[arrayname] are equivalent and point
to the first character in the string.
3/17/2021 7:45:49 AM 44
#include<stdio.h>
void main()
{
char city[]=“raju”;
int i=0;
printf(“Address\t\tContents\n”);
while(*(city+i)!=‘\0’)
{
printf(“%x\t %c\t %c\t %c\n”,
(city+i),city[i],*(city+i),i(city));
i++;
}
}
3/17/2021 7:45:49 AM 45
Address Contents
fff0 r r r
fff1 a a a
fff2 j j j
fff3 u u u

3/17/2021 7:45:49 AM 46
 An ‘array of pointers’ is similar to an array of any
predefined data type. As a pointer variable always
contains an address, an ‘array of pointer’ is a
collection of addresses. These can be addresses of
ordinary isolated variables or of array elements.
 The elements of an ‘array of pointers’ are stored in
the memory just like the elements of any other kind
of array. All rules that apply to other arrays also apply
to the ‘array of pointers’.
 For example:
a. int *a[5] declares an array of five integer pointers.
b. To make one of the pointers point to a variable one
might do the following: a[2]=&var;
c. To access the value pointed by a[2] we use *a[2]
which simply dereferences the pointer a[2] using *
operator. 3/17/2021 7:45:49 AM 47
#include<stdio.h>
void main() a[i] Value address
{ a[0] 2 FFF0
int a[3]={2,4,6}; a[1] 4 FFF2
int i, *ptr[3]; a[2] 6 FFF4
for(i=0;i<3;i++)
ptr[i]=&a[i];
printf(“a[i]\tValue\tAddress\n”);
for(i=0;i<3;i++)
printf(“a[%d]\t%d\t%p”,I,*ptr[i],ptr[i]);
}

3/17/2021 7:45:49 AM 48
 An array of pointers to strings is an array whose
elements are pointers to the base address of the
string.
 An array of pointers to strings is declared and
initialized in the following manner:
static char *pets[]={“Lion”, “Cat”};
where pets[0] is a pointer to the base address of
the string ‘Lion’, pets[1] is a pointer to the base
address of the string ‘Cat’ and so on.
 Unlike in the two dimensional array of characters
(array of strings), the strings do not have a fixed
memory size for storage. The strings occupy only
as many bytes required, hence, there is no
wastage ofspace.
3/17/2021 7:45:49 AM 49
 The strings need not be stored in consecutive memory
locations. The individual characters within the string
are accessed as usual using the indirection operator.
 The expression pets[i]+j points to the jth character of
the ith string.
Output:
 Example:
llo
void main() hhhh
{ eeee
llll
static char str[]=“hello”; llll
int i; oooo

printf(“%s\n”,str+2);
for(i=0;str[i];i++)
printf(“%c%c%c%c\n”,str[i],i[str],*(str+i),*(i+str));
}
3/17/2021 7:45:49 AM 50
 The process of allocating and freeing memory at run
time is known as dynamic memory allocation.
 This reserves the memory required by the program and
returns this resource to the system after the use of
reserved space.
 The programmer must know the size of the array or
data in advance while writing the program. In some
cases, it’s not possible to know the size of the memory
required in advance and to keep a lot of memory
reserved is not good practice. In such situation DMA is
useful.
 There are four library function malloc(), calloc(),
free() and realloc() for memory management. These
functions are defined within header file <stdlib.h> and
<alloc.h>.
3/17/2021 7:45:49 AM 51
 The conceptual view of storage of a C program is
shown in the fig. given below.
Local Variables Stack
Free Memory Heap
Global Variables Permanent
C Program Instructions Storage Area
Fig.: Storage of a C program
 The program instructions and global & static
variables are stored in a region known as
permanent storage area and the local variables are
stored in another area called stack.

3/17/2021 7:45:49 AM 52
 The memory space between these two regions is
available for dynamic memory allocation during
execution of the program. This free memory
region is called the ‘heap’.
 The size of the ‘heap’ keeps changing when
program is executed due to creation and death of
variables that are local to functions and blocks.
 Therefore, it is possible to encounter memory
“overflow” during dynamic memory allocation
process. In such situations, the memory allocation
functions mentioned above return a NULL pointer.
(when they fail to locate enough memory
requested).
3/17/2021 7:45:49 AM 53
 It is a memory management function included in
<stdlib.h> that dynamically allocates a block of
memory during program execution.
 It reserves a block of memory of specified size and
returns a pointer of type ‘void’ i.e. we can assign
it to any type of pointer.
 Syntax:
ptr=(cast_type *)malloc(byte_size);
where, ‘ptr’ is a pointer of type ‘cast_type’ and
‘malloc’ returns a pointer (of cast_type) to an
area of memory with size ‘byte_size’.

3/17/2021 7:45:49 AM 54
 Example:
x=(int *) malloc (100*sizeof(int));
when this statement is executed, a memory
space equivalent to ‘100 times the size of an
int’ bytes is reserved and the address of the
first byte of the memory allocated is
assigned to the pointer x of type ‘int’.
Similarly,
cptr=(char *) malloc(10);
allocates 10 bytes of space for the pointer
‘cptr’ of type ‘char’
3/17/2021 7:45:49 AM 55
cptr

Address of
the first byte

10 bytes of space

 The storage space allocated dynamically has no name and


therefore its contents can be accessed only through a
pointer.
 The ‘malloc’ allocates a block of contiguous bytes. The
allocation can fail if the space in the heap is not sufficient
to satisfy the request. If it fails, it returns a NULL. We
should therefore check whether the allocation is successful
before using the memory pointer.
3/17/2021 7:45:49 AM 56
#include<stdio.h>
#include<stdlib.h>
void main()
{ int n,I;
float *p, sum=0, avg; Output:
printf(“\nEnter the number of subject:”); Enter the no. of subject: 3
scanf(“%d”,&n); Enter marks of each course:
printf(“\nEnter marks of each course:”); 60
p=(float *)malloc(n*sizeof(float)); 70
for(i=0;i<n;i++) 80
{ scanf(“%f”,(p+i)); Sum of marks=210.00
sum+=*(p+i); Average marks=70.00
}
avg=sum/n;
printf(“\nSum of marks=%.2f”,sum);
printf(\nAverage marks=%.2f”,avg);
free(p);
}
3/17/2021 7:45:49 AM 57
 It is used to de-allocate a memory block
previously allocated by ‘malloc’, ‘calloc’ and
‘realloc’ i.e. it returns previously allocated
memory to the system.
 It’s our responsibility to release the space when
it is not required. The release of storage
becomes important when the storage is limited.
 Syntax:
free(pointer_variable)

3/17/2021 7:45:49 AM 58
 It is normally used for requesting memory space at run
time for storing derived data types such as arrays and
structures.
 malloc allocates a single block of storage space where
as calloc allocates multiple blocks of storage, each of
the same size, and then sets all bytes to zero.
 Syntax:
ptr=(cast_type *) calloc(n,elem_size);
The above statement allocates contiguous space for
‘n’ blocks, each of size ‘elem_size’ bytes. All bytes
are initialized to zero and a pointer to the first byte of
the allocated region is returned. If there is not enough
space, a NULL pointer is returned.
 It returns void pointers so they should be typecast to
the appropriate data type before using them to access
the memory allocated.
3/17/2021 7:45:49 AM 59
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *ptr,I,n;
printf(“\nEnter the size of integer array:”);
scanf(“%d”,&n);
ptr=(int *)calloc(n,sizeof(int));
printf(“\nEnter %d integers:”,n); Output:
for(i=0;i<n;i++) Enter the size of array:3
scanf(“%d”,&ptr[i]); Enter 3 integers: 11
22
printf(“\nThe elements are:”);
33
for(i=n-1;i>=0;i--) The elements are: 33 22 11
printff(“%d\t”,ptr[i]);
free(ptr);
}
3/17/2021 7:45:49 AM 60
 The ‘newsize’ may be larger or smaller than the
‘size’.
 It returns the address of the reallocated block, which
might be different from the address of the original
block.
 The new memory block may or may not begin at the
same place as the old one. If it is not able to find
additional space in the same region, it will create the
same in an entirely new region and move the contents
of the old block into the new block. The function
guarantees that the old data will remain intact.
 If the function is unsuccessful in locating additional
space, it returns a NULL pointer and the original block
is freed. This implies that it is necessary to test the
success of operation before proceeding further.
3/17/2021 7:45:49 AM 61
#include<stdio.h>
#include<stdlib.h>
void main()
{
char *buffer;
if(buffer=(char*)malloc(10))==NULL)
{ printf(“malloc failed”);
exit(1);
}
printf(“Buffer of size %d created.\n”,_msize(buffer));
strcpy(buffer,”kathmandu”);
printf(“Buffer contains:%s\n”,buffer);
/* Reallocation*/
if((buffer=(char*)realloc(buffer,15))==NULL)
{ printf(“Reallocation failed.\n”); exit(1); }
printf(“\nBuffer size modified.”);
printf(“\nBuffer still contains:%s”,buffer);
strcpy(buffer, “lalitpurpatan”);
printf(“\nBuffer now contains:%s”,buffer);
free(buffer);
}
3/17/2021 7:45:49 AM 62
#include<stdio.h>
#include<stdlib.h>
void main()
{ int n, i, j, *p, *temp;
printf(“\nHow many integers U wanna sort:”);
scanf(“%d”,&n);
p=(int *)malloc(n*sizeof(int)); printf(“\nEnter %d integers:”)
for (i=0;i<n;i++)
scanf(“%d”,(p+i));
for(i=0;i<n-1;i++)
{ for(j=i+1;j<n;j++)
{ if(*(p+i)<*(p+j))
{ *temp=*(p+i);
*(p+i)=*(p+j);
*(p+i)>*(p+j); } } }
printf(“Integers Sorted in descending order: ”);
for(i=0;i<n;i++)
printf(“%d\n”,(p+i));
}
3/17/2021 7:45:49 AM 63

You might also like