0% found this document useful (0 votes)
25 views

PSPC Unit-5

Uploaded by

manideepkm2006
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)
25 views

PSPC Unit-5

Uploaded by

manideepkm2006
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/ 56

PSTC UNIT-V POINTERS

5.1 Introduction to Pointers:


 Pointe is a variable which stores the address of another variable, since pointer is also kind
of a variable.
 Pointer itself will be stored at different memory location.
 Pointer variable prefix with *(Asterisk) symbol.

Syntax:
data_type * variable_name.

Example:
int *a; or int* a;

 In above declaration * placed in two different places ,the first one the * prefix with
variable and second one * followed by datatype both are right you will follow any one
these.

int i=24;
int *ptr; // declaration of pointer
ptr = &i; // assigning address into ptr

variable i ptr pointer

Value 24 11224

Address 11224 11001 address

 In above fig, i is a variable it holds the value 24 and address of I is 11224(let assume).
 Pointer always stores the address of variable so, ptr is a pointer , it stores the address of I (&i) i.e
11224.
 Pointer variable also stored at different location i.e 11001.

Variable name Value of variable Address of variable

i 24 11224

Ptr 11224 11001

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 1


PSTC UNIT-V POINTERS

Types of Pointers:

 According to data types generally pointer are two types :


1) Typed pointers
2) Un-typed pointer
 Typed pointers are nothing but integer pointers, character pointers, float pointers and
double pointers.

char * integer pointer


int * character pointers
float * float pointer one type of pointer cannot
double * double pointer points another type of data.

 Here one type of pointer cannot points another type of data that means integer pointer
can points only integer data only (integer pointer stores the int variable address only).
Character pointer points character data only, same as float and double.
 Un-typed pointer is nothing but generic pointers (void pointer). void pointer can point
any type of data.

void * void pointers

Size of pointers:

 The pointer occupy the same amount of memory for the all the data types, but how
much space they occupy will depends on the compiler where the code is going to
run.(like integer , integer size also differ from compiler to compiler.).
 .If we use 16bit compiler it occupy 2 bytes of memory for all data types , if we use 32
bit compiler the pointer occupies 4 bytes of memory .
 We will see the following table because the integer and pointer sizes are same based on
compilers.

Compiler Type int size Pointer size

16 bit 2 bytes 2 bytes

32 bit 4 bytes 4 bytes

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 2


PSTC UNIT-V POINTERS

Example :

Write a program to find the size of pointers with different data types

#include<stdio.h>

int main()

char *cptr;

int *iptr;

float *fptr;

double *dptr;

printf("\n The size of character pointer is: %d ",sizeof(cptr));

printf("\n The size of integer pointer is: %d ",sizeof(iptr));

printf("\n The size of float pointer is: %d ",sizeof(fptr));

printf("\n The size of double pointer is: %d ",sizeof(dptr));

return 0;

OUTPUT: (on 32 bit compiler)


The size of character pointer is: 4
The size of integer pointer is: 4
The size of float pointer is: 4
The size of double pointer is: 4

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 3


PSTC UNIT-V POINTERS

Declaring and initializing pointer variables:

 To declare a pointer variable like normal variable declaration with *.


int a=24;
int *ptr; // pointer declaration

 Here ptr is a pointer variable it stores the address of the variable, if we are not assign any
address to the pointer variable it stores the garbage value.

ptr= &a; // pointer initialization

 In this stores the address of the a is stored in ptr. When we will print the ptr then prints
the address of the a.
 To access the value inside a particular address, then we will prefix * with pointer name or
address i.e *ptr.

int a=24;
int *ptr; // declaration of pointer
ptr = &a; // assigning address into ptr

variable a ptr

Value 24 11224

Address 11224 11000

printf(“%d “,ptr) ; prints address i.e 11224

printf(“%d “,*ptr) ; prints value inside the address i.e 24


printf(“%d”,&ptr); prints address of the ptr is 11000

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 4


PSTC UNIT-V POINTERS

Example:
Explanation :
#include<stdio.h>
int main() i ptr
{
int i=100; 100 1241224
int *ptr;
ptr=&i; 1241224
printf("\n%d",i); 6122468
printf("\n%d",&i);
printf("\n%d",ptr);
printf("\n%d",&ptr);
printf("\n%d",*ptr); i=100
printf("\n%d",*(&i)); &i=1241224
return 0; ptr= 1241224
} &ptr=6122468
*ptr=100
*(&i)=100
OUTPUT:
100
1241224
1241224
6122468
100
100

Difference between * and & operators :

Address operator (&) Indirection operator ( * )

Pointer address operator is denoted by ‘&‘ Indirection operator is denoted by ‘*’ symbol
symbol When we use ampersand symbol as a when we use asterisk symbol as a prefix with
prefix to a variable name, it gives the address variable name, it gives the value which is
of that variable. inside specified address .it is also called as
lets take an example – &n - It gives an address value operator or dereferencing operator.
on variable n Working of address operator
#include<stdio.h> #include<stdio.h>
M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 5
PSTC UNIT-V POINTERS

void main() void main()


{ {
int n = 10; int n = 10;
printf("\nValue of n is : %d",n); printf("\nValue of n is : %d",n);
printf("\nValue of &n is : %u",&n); printf("\nValue of *n is : %u",*n);
} }
Output : Output :

Value of n is : 10 Value of n is : 10
Value of &n is : 1002 Value of &n is : 10

Consider the above example, where we have


used to print the address of the variable using
ampersand operator. In order to print the
variable we simply use name of variable while
to print the address of the variable we use
ampersand along with %u

printf("\nValue of &n is : %u",&n);

Understanding address operator Consider the


following program –
#include<stdio.h>
int main()
{
int i = 5;
int *ptr;
ptr = &i;
printf("\nAddress of i : %u",&i);
printf("\nValue of ptr is : %u",ptr);
return(0);
}

5.2 Pointer Arithmetic:


Incrementing Pointer: Incrementing Pointer is generally used in array because we have
contiguous memory in array and we know the contents of next memory location. Incrementing
Pointer Variable Depends Upon data type of the Pointer variable

Formula:

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 6


PSTC UNIT-V POINTERS

new value = current address + i * size_of(data type)

Three Rules should be used to increment pointer –

Address + 1 = Address

Address++ = Address

++Address = Address

Pictorial representation :

i ptr ptr
After
20 1224 1226
increment
1224 1508 1508

Next address stored in


Data Type Older address stored in pointer after increment
pointer (Ptr++)

Int 1224 1226


char 1224 1225

Float 1224 1228

Explanation :

 Incrementing a pointer to an integer data will cause its value to be incremented by 2 .


 This differs from compiler to compiler as memory required to store integer vary compiler
to compiler.
 Note to Remember : Increment and Decrement Operations on pointer should be used
when we have Continues memory (in Array).
Example 1 : Increment Integer Pointer

#include<stdio.h>

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 7


PSTC UNIT-V POINTERS

int main()

{
int *ptr=(int *)1000;
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
}

Output :
New Value of ptr : 1002

Example 2 : Increment Double Pointer


#include<stdio.h>
int main()
{

double *ptr=(double *)1000;

ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;

} Output :
New Value of ptr : 1008

Note :

 In C, the programmer may add or subtract integers from pointers, we can also subtract
one pointer from the other.
 An integer value can be added or subtracted from pointer variables but one pointer
variable cannot be added to another pointer variables. That mean only values can be
added.

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 8


PSTC UNIT-V POINTERS

Example :

int *ptr1=10;
int *ptr2=20;
*ptr1+*ptr2 it is possible i.e values can be added so the value is 30;
ptr+ptr2 Not possible i.e addresses cannot be added.

Example 3:

#include<stdio.h>
int main()
{
int x=10;
int y=25;
int *ptr1=&x;
int *ptr2=&y;
printf("x+y=%d",*ptr1+*ptr2);
return 0;
}

Output:
x+y=35

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 9


PSTC UNIT-V POINTERS

Example 4:

#include<stdio.h>
int main()
{
int n *p1,*p2;
p1=&n;
p2=p1+2;
printf("the difference between p1 & p2 is %d memory segments”,p2-p1);
return 0;
}

Output: the difference between p1 & p2 is 2 memory segments

Explanation:

Statement Value in p1 Value in p2

int n,*p1,*p2 Garbage value Garbage value

p1=&n 1000 Garbage value


p2=p1+2 1000 1008

p2-p1 1008-1000=8 bytes (int occupies 4 bytes for each element,


so, 8 bytes for 2 elements.)

Interview Problem: find the output for following program

#include<stdio.h>

int main()

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

int *ptr;

ptr=arr;

printf("%u\n",*++ptr+3); statement1

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 10


PSTC UNIT-V POINTERS

printf("%u\n",*(ptr--+2)+5); statement2

printf("%u\n",*(ptr+3)-10); statement3

return 0;
OUTPUT:
} 23
45
30

Explanation:

arr[5]={10,20,30,40,50}

10 20 30 40 50

arr 1000 1002 1004 1006 1008

1000

ptr ptr=arr or ptr=&arr or ptr=arr[0];

1000
Statement 1:

*++ptr+3 (R to L)

*1002+3

20+3 => 23

Statement 2:

*(ptr - - +2)+5

*(1002 +2)+5

*1006+5

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 11


PSTC UNIT-V POINTERS

40+5 => 45

Statement 3:

*(ptr+3)-10

*(1000+3)-10

*1006-10

40-10 => 30

5.3 NULL Pointer:


 Null pointer which is a special values that does not point anywhere, this means that
NULL pointer does not point to any valid memory address .
 To declare a null pointer you may use the predefined constant NULL, which is defined in
several standard header files i.e <stdio.h> , <stdlib.h> and <string.h> .
 The NULL is a constant in c, it returns value is 0.
 If any pointer does not contain valid memory address or pointer is uninitialized, then the
pointer is a null.
 We can also assign 0 or NULL to make a pointer as “NULL pointer” .

Example : int *ptr==NULL

Example 1: Example 2:

#include<stdlib.h> #include<stdio.h>
int main() #include<stdlib.h>
{ int main()
int * ptr=NULL; {
printf("the value of ptr is :%x",ptr); int num=24;
if(ptr) int *ptr1=&num;
printf("\nPointer is not a NULL pointer"); int *ptr2;
if(!ptr) int *ptr3=0;
printf("\nPointer is a NULL pointer"); if(ptr1==0)
return 0; printf("\nPointer 1 : NULL");
else
} printf("\nPointer 1 : NOT NULL");
if(ptr2==0)
printf("\nPointer 2 : NULL");
OUTPUT: else
pointer is a NULL pointer printf("\nPointer 2 : NOT NULL");
if(ptr3==0)
printf("\nPointer 3 : NULL");
else

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 12


PSTC UNIT-V POINTERS

printf("\nPointer 3 : NOT NULL");


return 0;

OUTPUT:
Pointer 1: NOT NULL
Pointer 2: NULL
Pointer 3:NULL

 ptr1 is initialized with address of num.


Thus,ptr1 contains valid memory
address .
 ptr2 is uninitialized, it contains garbage
value i.e not valid memory address and
ptr3 assigned 0. Thus , ptr2 and ptr3 are
the NULL pointers,

Note:

 A runtime error is generated if you try to dereference a null pointer.


Example:
int *ptr=NULL;
printf(“ Address %d”,ptr); it gives the output 0
printf(“ Value %d”,*ptr); Generate logical error at run time.

5.4 Generic pointers (Void Pointers):


 Generic pointer is a pointer variable that has void as its data type
 It is also called as void pointer.
 It can be used to point to variable of any data type. It declare like pointer variable but
using ‘void’ keyword as pointer data type.

Ex: void *ptr


 In c, since we cannot have a variable of type void.
 A pointer variable of type void * cannot be referenced. We need to type cast a void
pointer to another kind of pointer before using it.

Example :

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 13


PSTC UNIT-V POINTERS

#include<stdio.h>

int main()

int x=10;

char ch='R';

void *gp; // generic pointer

gp=&x; // assigning integer address to void pointer

printf("\ngeneric pointer points to the integer %d",*(int *)gp);

gp=&ch; // assigning character address to void pointer.

printf("\n generic pointer points to the character %c",*(char *)gp);

return 0;

Note : A compilation error will be generated if we assign a pointer of one type to a pointer of
another type without a cast.

5.5 Pointers as function Arguments:


 We know that, it is impossible to modify the actual arguments when we pass them to a
function, the incoming arguments to a function are treated as local variables in the
function and those local variables get a copy of values passes from their calling functions.
This technique is known as call by value.
 Pointers provide a mechanism to modify data declared in one function using code written
in another function.
 The calling function sends the addresses of the variables and the called function must
declare those incoming arguments as pointers. In order to modify the variables sent by
the calling function, the called function must dereference the pointer that we are passed it.
This technique is known as call by reference.
 To use pointers for passing arguments to a function, the programmer must do the
following steps:
 Declare the function parameters as pointer
 Use the dereferenced pointer in function body
 Pass the address as the actual argument when the function is called.

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 14


PSTC UNIT-V POINTERS

Example:

#include<stdio.h>

void sum(int*,int*,int*);

int main()

int num1,num2,total;

printf("\n Enter two values num1 & num2:");

scanf("%d%d",&num1,&num2);

sum(&num1,&num2,&total);

printf("\Total =%d",total);

return 0;

void sum(int *a,int *b,int *t)

*t=*a+*b;

OUTPUT:
Enter two value num1 & num2:
10
20
Total = 30

5.5.1 Parameter passing mechanism:


There are two ways that a C function can be called from a program. They are,

1. Call by value
2. Call by reference

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 15


PSTC UNIT-V POINTERS

Call by Value

In call by value method, the value of the variable is passed to the function as
parameter. The value of the actual parameter cannot be modified by formal parameter. Different
Memory is allocated for both actual and formal parameters. Because, value of actual parameter is
copied to formal parameter.

Example Explanation:
#include<stdio.h>
void swap(int , int ); main (calling function)
int main()
{ 24 7
int a = 24, b = 7;
printf("\nValues before swap \n a = %d and b = %d", a, b); 27 27
2048 2017
swap(a,b);
printf(" \nValues after swap \n a = %d and b = %d", a, b); swap (called function)
return 0;
}
x y
void swap(int x, int y) 24 7 7 24
{
2049 2785
int temp; temp
temp = x;
24
x = y;
y = temp; 7000
}

OUTPUT
Values before swap
a =24 and b = 7
Values after swap
a =24 and b = 7

Call by reference

In call by reference method, the address of the variable is passed to the function as
parameter. The value of the actual parameter can be modified by formal parameter. Same
memory is used for both actual and formal parameters since only address is used by both
parameters.

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 16


PSTC UNIT-V POINTERS

Example:
#include<stdio.h> main (calling function)
void swap(int *, int *);
int main() 24 7 7 24
{
int a = 22, b = 44; 2048 27
2017
printf("\nValues before swap \n a = %d and b = %d", a, b);
swap(&a,&b); 27
swap (called function)
printf(" \nValues after swap \n a = %d and b = %d", a, b);
x y
return 0;
} 2048 2017
void swap(int *x, int *y)
2049 2785
{ temp
int temp; 24
temp = *x;
*x = *y; 7000
*y = temp;
}

OUTPUT:
Values before swap
a =22 and b = 44
Values after swap
a =44 and b = 22

5.6 POINTERS & ARRAYS :


 An array occupies consecutive memory locations.
int arr[ ] = {1,2,3,4,5};
a[0] a[1] a[2] a[3] a[4]

1 2 3 4 5
100 102 104 106 108
 The name of the array is the starting address of array in memory. It is
also known as “Base address “.

int *ptr;
ptr = &arr[0];
 Ptr is made to point the first element of the array.

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 17


PSTC UNIT-V POINTERS

Ex:-
main( )
{
int arr[ ]={1,2,3,4,5};
printf(“Address of array=%p %p %p”,arr,&arr[0],&arr);
ptr =&arr[2];

1 2 3 4 5
100 102 104 106 108
ptr =arr[3];
 If pointer variable ptr holds the address of the first element in the array.

int *ptr =&arr[0];


ptr++;
printf(“The value of the second element of array is %d”,*ptr);
}

Note:-
An error is generated if an attempt is made to change the address of the array.

Example 1:
#include <stdio.h>
int main( )

int a[ ]={1,2,3,4,5,6,7,8,9};
int *p1,p2;
p1=a; OUTPUT:
123456789
p2=&a[8];
while(p1<=p2)
{

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 18


PSTC UNIT-V POINTERS

printf(“%d\t”,*p1);
p1++;
}

return 0;
}

Example 2:
int main( )
{
int arr[ ]={1,2,3,4,5};
int *ptr,i;

ptr=&arr[2];
*ptr= 24;
*(ptr+1)=0;
*(ptr-1)=1;
printf(“\n array is”);
for(i=0;i<5;i++)

{ OUTPUT:
1 1 24 0 5
printf(“%d\t”,*(arr+1));
}
}

5.7 Pointers to constant:


 The value of the variable to which the pointer is pointing is constant variable.
 That means, a pointer through which one cannot change the value of the variable to
which is known as “pointer to constant”.

Syntax-1
const <type of pointer> *<pointer name>

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 19


PSTC UNIT-V POINTERS

Ex:-
const int *ptr;

(OR)
Syntax-2
<type of pointer> const *<pointer name>

Ex:-
int const *ptr;

 These pointer can change the address the point to but cannot change the value at the
address they are pointing to.
Ex:-
main( )
{
int a=10;
cons tint *ptr=&a; ptr to const value.
*ptr=30; error because value we can’t change
return 0;
}
a b a 30 b
Example:2
10 20 10 20
main() 30
{ 1024 1026 30
1024 not ok 1026
//Definition of the variable. 30
int a=10; 1024
1024
int b=20;
const int*ptr=&a; 1029 1029
ptr=&b; It works because address is not constant.
return 0;
}
1) const int *ptr=&a;
a b

10 20
1024 1026

1024 1026

const int *p=&a;


ptr=&b;

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 20


PSTC UNIT-V POINTERS

5.8 Constant pointers:


 A constant pointer is one that cannot change address it contains.
 In other words, we can say that once a constant pointer points to a variable it cannot point
to any other variable.
Note:- However ,these pointer can change the value of the variable they point to but
cannot change the address they are holding.

Syntax:- <type of pointer>*const <pointer name>

Ex: int *const ptr

Constant pointer Value change Address change


int * const ptr Possible Not possible

Example Value constant Pointer constant


char *ptr No No
const char *ptr Yes No
char const *ptr Yes No
char *const ptr No Yes
const char *const ptr Yes Yes
Example:
int main( )
{
int a=10;
int b=20;
const int *ptr=&a;
*ptr=30; possible, we can change the value of ptr
ptr=&b; Error because we can’t change the address of ptr.
return 0;
}

1) int *const ptr=&a; *ptr=30;


a b a b
10 20 10 30 20

1000 1024 1000 1024


ptr

1000 1000

3001 3001

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 21


PSTC UNIT-V POINTERS

2) int *const ptr=&a;

ptr=&b; error we can’t change the adrees

a b

10 20
1000 1024

1000
3001
3000

Trick to remember constant pointer and pointer to constant:


 Easy to identify the pointer constant and constant pointers observe the following table

Example before asterisk(*) Part after asterisk(*) Description


const char *ptr const char Ptr const is associated
with data type so ,
value is constant.
char const *ptr char const Ptr const is associated
with data type so ,
value is constant.
char *const ptr Char const ptr const is associated
with pointer so ,
pointer is constant.
const char *const ptr const char const ptr const is associated
with both so ,both are
constant.

Note : In above table we observe 3 things


1. const keyword placed before the asterisk (*) then that pointer is known as pointer to
constant ( value is constant ).
2. const keyword placed after the asterisk (*) then that pointer is known as constant pointer
(address is constant).
3. const keyword placed both sides i.e before and after asterisk (*) then the pointer is both
pointer to constant and pointer to constant.

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 22


PSTC UNIT-V POINTERS

5.9 Pointers to pointers:-


 As we know , a pointer is used to store the address of a variable in C. Pointer reduce the
access time of variable.
 We can also defined a pointer to store the address of another pointer. Such pointer is
known as double pointer (pointer to pointers)
 The first pointer is used to store the address of a variable whenever the second pointer is
used to store the address of the first pointer.

1)int a=24; a p pp
int *p=&a;
int **pp=&p; 24 1000 2000
1000 2000 3000
 a is a variable stored at 1000 location. p is pointer which contains the address or a
variable and pp is double pointer which contains the address of p pointer.

**pp Explanation:
 It will give value at location 2000 ,which is 1000.
 **p will give the value at location 1000 , which is 24.
 Value of **pp=24
 Value of *p=24
 Value of a=24
 Value of p=1000
 Value of pp=3000
 Value of &a=1000

Example :
int main( )
{
int num=7;
int *p,**pp;
p=&num;
OUTPUT:
pp=&p; Adreess of number variable 644523
Adreess in p variable 644523
printf(“\n%d address of number variable”,&num); Value of *p is 7
printf(“\nAddress in p variable-%d”,p); Adreess in pp is 521342
Value of *pp is 644523
printf(“\nValue of *p is %d”,*p); Value of **pp is 7

printf(“\nAddress of pp is %d”,pp);
printf(“\nValue of *pp is %d”,*pp);

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 23


PSTC UNIT-V POINTERS

printf(“\nValue of **pp is %d”,**pp);


return 0; }
Note : In double pointer (pointer to pointer ) ,we can also prefix the more than two ** to pointer
variable. If we declare more pointers what will happen ? observe the following.

Example 2 :
#include<stdio.h>
int main( )
{ OUTPUT:
int a=24; address of variable a: 1224
int *p,**pp,***ppp,****pppp; value of variable *p : 24
p=&a; adress of pp is: 6453
pp=&p; Address * pp is : 1224
ppp=&pp; Value of **pp is: 24
pppp=&ppp; adress of ppp is 7624
printf("%d\n address of variable a : ",p); Address in * ppp is:6453
printf("\n value of variable a :%d",*p); adresss of**ppp is:1224
printf("adress of pp is: %d",pp); value inside ***ppp is 24
printf("\n Address inside pp is %d",*pp); adress of pppp is: 9234
printf("\n Value of **pp is: %d",**pp); Address * pppp is: 7624
printf("adress of ppp is: %d",ppp); adresss of **pppp is 6453
printf("\n Address inside ppp is %d",*ppp); adress inside ***pppp is: 1224
printf("\n adresss of *ppp is: %d",**ppp); value inside the ****pppp: 24
printf("\n value inside ***ppp is:%d",***ppp);
printf("adress of pppp is: %d",pppp);
printf("\n Address inside pppp is %d",*pppp);
printf("\n adresss of *pppp is: %d",**pppp);
printf("\n adress inside ***ppppis:%d",***pppp)
printf("\n value inside the ****pppp is
:%d",****pppp);
return 0;
}
Explanation :
a p pp ppp pppp
1224 9234
24 6453 7624
1224
6453 7624 9234 3879

p=1224 pp=6453 ppp=7624 pppp=9234


*p=24 *pp=1224 *ppp=6453 *pppp=7624
**pp=24 **ppp=1224 **pppp=6453
***ppp=24 ***pppp=1224
****pppp=24

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 24


PSTC UNIT-V POINTERS

5.10 Pointers & strings:-


String is nothing but array of character terminated with ‘\0’.
1. char str[10];
str[0]=’c’;
str[1]=’s’;
str[2]=’e’;
str[3]=’\0’;
2. char str[10]={‘c’,’s’,’e’,’\0’};
3. char str[10]=”cse”;

 when the double quotes are used ,NULL character (‘\0’) is automatically appends to the
end of string.
 When a string is declared like this the compiler sets avoid a contiguous block or memory
10 bytes long to hold characters and initiate its first four characters cse\0 .

Example:
#include <stdio.h>
int main
()
{
char str[ ]=”Hello Cse”; OUTPUT:
char *pstr; Hello Cse

pstr=str;
printf(“\n the string is:”);
while(*pstr!=’\0’)
{
printf(“%c”,*pstr);
pstr++;

}
return 0;
}

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 25


PSTC UNIT-V POINTERS

 In this program, we declare pointer *pstr to show the string on the screen. We then point
the pointer pstr at str. Then we print each character of the string in the while loop. Instead
of using while loop, we could have directly use the function puts

puts(pstr);  it prints entire string

The function prototype for puts :


int puts(const char *s);
 Here the const modifier is used to assure the user that the function will not modify the
contents pointed to by the source pointer. The address of the string is passed to the
function as an arguments.

 The parameter passed to puts() is a pointer which is the address to which it points to, an
address .thus writing puts(str) i.e means passing the address of str[0].

By writing puts(str) str means address or str[0].

Similarly when we write puts(pstr)


Pstr=str;

#include <stdio.h>
void main( )
{
char str[100],*pstr;
int upper=0,lower=0;
printf(“\n Enter the string:”);

gets(str);
pstr=str;
while(*pstr!=’\0’)
{
if(*pstr>=’A’ && *pstr <=’Z’)
upper++;

else if(*pstr>=’a’ && *pstr<=’z’)


lower++;
pstr++;

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 26


PSTC UNIT-V POINTERS

}
printf(“The total number of capitals is %d”,upper);
printf(“The total number of lower letters is %d”,lower);

Difference between array name & pointer:-


1. Array address cannot be changed but pointer address will be changed.
#include <stdio.h> #include <stdio.h>
void main( ) void main( )
{ {
int arr[5],i; int arr[5],i,*parr;
for(i=0;i<5;i++) parr=arr;
{ for(i=0;i<5;i++)
*arr=0; {
arr++;//Error *parr=i;
} parr++;
for(i=0;i<5;i++) }
{ for(i=0;i<5;i++)
Printf(“%d”,*(arr+i)); {
} Printf(“%d”,*(parr+i));
} }
}
2. array cannot be assigned to another array.
int arr[ ]={1,2,3,4,5,6};
int arr2[6];
arr2=arr; //Error
But one pointer variable can be assigned to another pointer variable of the same type
int arr[ ]={1,2,3,4,5,6},*ptr1,*ptr2;
ptr1=arr1;
ptr2=ptr1;

1 2 3 4 5 6
102 104 106 108 110 112

Ptr1

3. The address operator returns the address the operand .But when an address operator is
applied to an array name. If gives the same value without the operator.

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 27


PSTC UNIT-V POINTERS

4. Size of operator
#include <stdio.h>
void main( )

{
int arr[ ]={1,2,3,4,5};
int *ptr;
ptr=arr;
printf(“The size of array=%d”,sizeof(arr));  it give size of array i.e 20
printf(“The size of pointer=%d”,sizeof(ptr)); it gives size of pointer i.e 2
}

5.11 Function pointers (pointers to functions):-


 Every function code along with its variable is allocated some space in the memory.
 Function pointers are pointer variable that point to the address of a function.
 Like other pointer variable ,function pointer can be declared, assigned value and used to
access the function they point to.
 This is a useful technique for passing a function as argument to another function.
 In order to declare a pointer to a function we have to declare its prototype of the except
that the name of a function enclosed between parentheses. ( ) and an (*) is inserted before
name.
 It is possible to declare pointers to functions . But ,if you want to create a pointer to
function the declaration is completely depends on the function prototype.

Declaration of function pointer:


Syntax :

return_type(*pointer_name) (arguments list);

Example: E
int (*ptr) (int,int);

It can point to any function ,Which is taking integer argument & return
int data type.

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 28


PSTC UNIT-V POINTERS

Note :
 ptr-name we must place inside the parentheses along with pointer(*). Why we declare
pointer name within the parenthesis.
 If we declare pointer name without parenthesis ,it changes the total format, to clear
understand observe the following .

Declaration of function pointer is

int (*ptr) (int, int)

Now, We re –write the above statement without using parenthesis for function pointers
int * ptr (int,int)
In above function, ptr is a function which takes two integer arguments and it returns address of
integer variable (int*) .
When we declare ptr is a normal function, it returns the integer address . its not function pointer.
so, In function pointer we must declare pointer name within parenthesis otherwise compiler
consider as normal function it returns integer address.

Initialization of function pointer:


 if we have declared a pointer to a function, then that pointer can be assigned the address
of the correct function jusy by its name.
 function name always holds the starting address (base address) of the function, it is
optional to use the address operator (&) in front of function name.
 if fp is a function pointer and we have a function add() then,

int (*fp)(int,int)  function pointer declaration

int add (int,int )  function declaration

fp=add; or fp= &add  function pointer points to the add function

 When we assign the address of function to pointer , the arguments size,type and return
type should be match, otherwise it gives error i.e incompatible error.

int mul(int,int,int)

fp=mul or &mul error, incompatible error because function pointer


having two arguments but mul function having
three arguments.

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 29


PSTC UNIT-V POINTERS

Calling functional pointer :


 When a pointer to a function is declared ,it can be called in two ways

(*fp)(10,20) OR fp(10,20)

Example 1:
#include <stdio.h>
int mult(int x,int y,int z);
int add(int x,int y);
int main( )

{
int res1,res2,res3;
int (*ptr) (int,int); function pointer declaration, it is also declare abovethe main also
res1=add(10,20); function call without using function pointers.
res2=mult(2,3,4);
printf(“Before using function pointers %d,%d”,res1,res2);

ptr=&add;  assign the function address to function pointers


res3=ptr(30,50); or (*ptr)  calling functional pointer
printf(“After using function pointers %d”,res3);
// ptr=&mult; Error , incompatible pointer assignment.
return 0;
}

int add(int x,int y)


{
int z=x+y;
return z;
}

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 30


PSTC UNIT-V POINTERS

int mult(int x,int y,int z)


{
int n=x*y*z;

return n;
}

OUTPUT:
Before using function pointers 30 24
After using function pointer 30

Example 2:
#include<stdio.h>
void display(int n);
void (*fp) (int);
int main()
{

fp=display; // assigning function address into function pointer


if(fp>0) // Comparing function pointers
{
if(fp==display)
printf("\n The pointer points to the display function");
else

printf("\n the pointer points to the display function");


}
fp(24); // function pointer calling
(*fp)(10); // function pointer calling again with different value
return 0;

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 31


PSTC UNIT-V POINTERS

}
void display(int n)
{

printf("\n %d",n);
}

OUTPUT:
The pointer points to the display function
24
10

5.12 Passing a function pointer as an argument to a function:-


 A function pointer can be passed as the calling arguments of a function.
 It is necessary if you want to pass a pointer to a call back.
 Like normal pointer, function pointer can be passed as argument and can also be return
from a function.

Example 1:
#include<stdio.h>
void cse4();
void cse5();
void e1cse(void (*csedep) ()); // function declaration with argument as function
int main() pointers
{
e1cse(cse4); // function call here pass the address of cse4() function
e1cse(cse5); // function call here pass the address of cse5() function

return 0;
}
void e1cse(void (*csedep) ()) // function definition
{
csedep(); // calling function pointers
(*csedep)(); // calling function pointers again
}
void cse4()
{
printf("\n Hi....Im CSE4");
}

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 32


PSTC UNIT-V POINTERS

void cse5()
{
printf("\n Hi....Im CSE5");
}

OUTPUT:
Hi….Im CSE4
Hi….Im CSE4
Hi….Im CSE5
Hi….Im CSE5

Example 2: Arithmetic operation using pointers as arguments.


#include<stdio.h>
void add();
void sub();
void mul();
void div();

void maths(void (*arthmetic) ());


int main()
{
maths(add);
maths(sub);
maths(mul);

maths(div);
return 0;
}
void maths(void (*arthmetic) ())
{
(*arthmetic)();

}
M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 33
PSTC UNIT-V POINTERS

void add()
{
int sum,a,b;

printf("Enter 2 numbers to be add\n");


scanf("%d%d",&a,&b);
sum=a+b;
printf(" The addition of two numbers are:%d \n ",sum);
}
void sub()
{

int dif,a,b;
printf("Enter 2 numbers to be sub \n");
scanf("%d%d",&a,&b);
dif=a-b;
printf("The difference of two numbers are:%d \n ",dif);
}

void mul()
{
int mulp,a,b;
printf("Enter 2 numbers to be multiplication\n");
scanf("%d%d",&a,&b);
mulp=a*b;

printf(" The multiplication of two numbers are:%d \n",mulp);


}
void div()
{
int dvv,a,b;

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 34


PSTC UNIT-V POINTERS

printf("Enter 2 numbers to be division \n");


scanf("%d%d",&a,&b);
dvv=a/b;

printf("The division of two numbers are:%d \n ",dvv);


}

OUTPUT:
Enter 2 numbers to be add
10
20
The addition of two numbers are : 30
Enter 2 numbers to be sub
24
17
The addition of two numbers are : 7
Enter 2 numbers to be multiplication
6
4
The addition of two numbers are : 24
Enter 2 numbers to be division
169
13
The addition of two numbers are : 13

5.13 Passing arrays to a function


 If you want to pass an array as an arguments in a function ,we have to declare a
formal parameters in the one of following three ways and all there declaration
methods similar results because that an integer pointer is going to be received similar.
Syntax-1:- (Formal parameters as pointer)
void fun(int *param)
{
--------
---------
}
Syntax-2:- (Formal parameters as sized array)
Void fun(int *param[10])
{
--------
---------
}

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 35


PSTC UNIT-V POINTERS

Syntax-3:- (Formal parameters as unseized array)


Void fun(int *param[ ])
{
--------
---------
}

Write a program to addition of array elements in 3 ways.

Program-1:- (Formal parameters as pointer)


#include <stdio.h>
void disp(int *num);
void main( )
{
int i,arr[ ]={1,2,3,4,5};
for(i=0;i<size;i++)
{
disp(&arr[i]);
}
}
void disp(int *num)
{

Printf(“%d”,*num);
}

Program-2:- (Formal parameters as sized array)

#include <stdio.h>
int sum(int arr[ ],int size);
void main( )
{
int arr[ ]={1,2,3,4,5};
int total;
total=sum(arr,5);
printf(“Sum of array is %d”,total);
}
int sum(int arr[ ],int size)
{
int i;
int sum1=0;
for(i=0;i<size;i++)

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 36


PSTC UNIT-V POINTERS

{
sum1+=arr[i];
}
return sum1;
}

Program-3:- (Formal parameters as unseized array)

#include <stdio.h>
int sum(int *arr,int size);
void main( )
{
int arr[ ]={1,2,3,4,5};
int total;
total=sum(arr,5);
printf(“Sum of array is %d”,total);
}
int sum(int *arr,int size)
{
int i,int sum=0;
for(i=0;i<size;i++)
{
sum+=arr[i];
}
return sum;
}

Same output for the above 3 programs

OUTPUT:
Sum of array is : 15

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 37


PSTC UNIT-V POINTERS

5.14 Array of pointers :


 array of pointer is an array of the pointer variable. It is also known as pointer array,
 We know that array is a variable it stores the more than one value inside it. Similarly,
array pointer means it stores more than one address inside the array is known as array
of pointers.

Syntax:-
int *var_name [array_size];

Declaration of array of pointers :-


int *ptr [3];

 To read (to scan) and write (to print) array of pointers in to ways :
1. Through Index values.
2. Using pointer arithmetic / modifier

While writing pointers program, we prefer pointer arithmetic to easy to understand, its
no problem to index values also.

Example 1:
#include <stdio.h> 0 1 2 3 4

void main( ) a 10 20 30 40 50

{ 102 102 104 106 108 110


int i,a[5]={10,20,30,40,50};
int *p[5]; p 0 1 2 3 4
for(i=0;i<5;i++) 701 102 104 106 108 110
{ 701 703 705 707 709
p[i]=&a[i];  through index values

(or)
*(p+i)=a+i;  using pointer arithmetic
}
}
for(i=0;i<5;i++)
M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 38
PSTC UNIT-V POINTERS

{
printf(“%d\n”,a[i]);  through index value

or
printf(“%d\n”,*(a+i));  pointer arithmetic

or
printf(“%d\n”,*p[i]);  pointer through index values

or
printf(“%d\n”,**(p+i));  using pointer arithmetic
}

Example 2:
#include <stdio.h>
int main( )
{ a b c
int a,b,c;
int *ptr[3];
10 20 30
ptr[0]=&a, ptr[1]=&b, ptr[2]=&c; 10254 24325 45321

a=10,b=20,c=30;
printf(“%d\t%d\t%d”,*p[0], *p[1], *p[2]);
10254 24325 45321
*ptr[0]*=30;
*ptr[1] - =5; 1024 1026 1028
*ptr[2]+=6; ptr
printf(“%d,%d,%d”,*p[0], *p[1], *p[2]);
1024
return 0;
}
OUTPUT:
10 20 30
300 15 36

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 39


PSTC UNIT-V POINTERS

5.15 Memory allocation in C:


There are 2 kinds of memory allocation.
1. Static Memory Allocation
2. Dynamic Memory Allocation

Static Memory allocation:


 It is fixed size of memory, the no. of bytes reserved for the variable cannot be changing
during the execution of a program. Example : Arrays
 The static memory is constant, no one can change it.
 At static memory allocation, compiler can recognize how much memory occupied by the
program.

5.16 Dynamic Memory Allocation:


 Dynamic Memory Allocation is not fixed, the no.of bytes reserved for the variable we
can be changing during the execution of the program.
 It is a not fixed size of memory and not constant.
 Dynamic Memory Allocation in C Language is possible by 4 functions.

1. malloc( )
2. calloc( )
3. realloc( )
4. free( )
 These 4 functions are included in stdlib.h
 When we are using dynamic memory allocation, then memory allocated in heap memory.

1. malloc( ) : ( Memory allocation)


 The malloc() function reserves a block of memory of specified size and pointers of type
void *(generic pointer).
Prototype :
void * malloc(size of array *sizeof_datatype

Syntax:
ptr= (cast_type*) malloc (byte_size)
where ptr is a pointer, malloc( ) function returns the base address of the memory .

 The malloc( ) function successfully completed,it reserves memory, it returns base


address.
 The malloc( ) function on failure, it reserves not reserve any memory, it returns null
pointer.

Ex:

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 40


PSTC UNIT-V POINTERS

ptr=(int *)malloc(10*sizeof(int));

 malloc( ) function having single argument.


 malloc( ) function specially for structures. It is also possible for allocation of memory for
arrays also. But this function specially dynamic memory allocation for structures.
 The default value is garbage value.

Example 1: ( To Create arrays by using malloc( ) )

#include<stdio.h>
OUTPUT:
#include<stdlib.h> Enter no.of elements you want 4
Enter the index 0 of the array 10
int main() Enter the index 1 of the array 20
Enter the index 2 of the array 30
{ Enter the index 3 of the array 40
The array contains
int n,i; 10 20 30 40
printf("Enter no.of element you want");

scanf("%d",&n); arr[0] arr[1] arr[2] arr[3]


int *arr;
10 20 30 40
arr=(int *)malloc(n*sizeof(int));

if(arr==NULL) 102 104 106 108


{
Arr
printf("\n The NO Space in memory
102
allocation is failed");

exit(0);

for(i=0;i<n;i++)

printf("\n Enter the Index %d of the array",i);

scanf("%d",&arr[i]);

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 41


PSTC UNIT-V POINTERS

printf("\n The array contains\n");

for(i=0; i<n; i++)

printf("%d\t",*(arr+i));

free(arr);

return 0;

Example 2: ( To Create structure using malloc( ) function)

#include<stdio.h>

#include<stdlib.h> When we are using malloc() for structures memory


allocated like below..
struct student

int sid;
sid sname smarks
char sname[10]; 102 104 114
(2bytes) (10bytes) (4bytes)
float smarks;
Ptr
}; 102

int main()

{
OUTPUT:
struct student *ptr;
Enter student ID: 1224
ptr=(struct student*)malloc(sizeof(struct student)); Enter student name: Ram
Enter student marks: 8.7
if(ptr==NULL)
Student Details Are:
{ ID NO:1224
NAME: Ram
printf("No storage space"); CGPA:8.7

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 42


PSTC UNIT-V POINTERS

else

printf("Enter student ID:");

scanf("%d",&ptr->sid);

printf("Enter student name:");

scanf(" %s",ptr->sname);

printf(" Enter student marks:");

scanf("%f",&ptr->smarks);

printf("Student Details Are:");

printf("\n ID NO:%d ",ptr->sid);

printf(" \n NAME: %s",ptr->sname);

printf("\n CGPA:%f",ptr->smarks);

Note: When we are using structures with pointer then we have to access the elements with arrow
(->) operator.

2. calloc() (Contiguous memory allocation):


 calloc() is nothing but continuous memory allocation that is happed in arrays.so, calloc()
function creates dynamic memory allocation for only arrays.

 This function allocates multiple blocks of request memory with specified size.

Prototype :

void *calloc(sizeof array,size of each element);

Syntax :

ptr= (cast_type *) calloc (no of elements,size of each elament);

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 43


PSTC UNIT-V POINTERS

where ptr is a pointer, calloc( ) function returns the base address of the memory .
 The calloc( ) function successfully completed,it reserves memory, it returns base address.
 The calloc( ) function on failure, it reserves not reserve any memory, it returns null
pointer.

Ex:

ptr=(int *)calloc(10*sizeof(int));

 In calloc( ), all elements are initialized with 0’s if we not assigned any values.

Example:
OUTPUT:
#include<stdio.h> Enter no.of elements you want 4
Enter the index 0 of the array 10
#include<stdlib.h> Enter the index 1 of the array 20
Enter the index 2 of the array 30
int main() Enter the index 3 of the array 40
The array contains
{
10 20 30 40
int n,i;

printf("Enter no.of element you want");


arr[0] arr[1] arr[2] arr[3]
scanf("%d",&n);
10 20 30 40
int *arr;

arr=(int *)calloc(n,sizeof(int));
102 104 106 108
if(arr==NULL)
Arr
{
102
printf("\n The NO Space in memory
allocation is failed");

exit(0);

else

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 44


PSTC UNIT-V POINTERS

for(i=0;i<n;i++)

printf("\n Enter the Index %d of the array",i);

scanf("%d",&arr[i]);

printf("\n The array contains\n");

for(i=0; i<n; i++)

printf("%d\t",*(arr+i));

free(arr);

return 0;

Difference between malloc() and calloc():

S.No malloc() calloc()

1 malloc() means memory allocation. this calloc() means contiguous memory


function reserves a block of memory of allocation. Continuous memory allocation
specified size. Ex : structures happen at arrays. this function reserves
by using malloc() specially allocating multiple blocks block of memory of
memory for structures. It is also possible specified size. Ex: arrays
to allocate memory for arrays also. by using calloc() specially allocating
memory for arrays only because continues
memory blocks occurs in array.

2 In this, default value garbage value if we In this, default value zero. If we Not any
are not initialized any value, values, then the compiler initialized with zero
to all array elements.

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 45


PSTC UNIT-V POINTERS

3 malloc() function takes single argument calloc() function takes two arguments

Ex: (int *)malloc(n*sizeof(int)) Ex: (int *)malloc(n,sizeof(int))

4
malloc() is faster than calloc(). calloc() is slow compare to malloc
beacauseof the extra step of initializing the
allocated memory by zero..

3.realloc( ): (Memory reallocation )


 Memory reallocation is nothing but at the time memory allocated by using calloc() or
malloc( ) might be sufficient or in excess, that means to increase or decrease the memory.
 We can always use realloc( ) function to change the memory size already allocated by
calloc( ) and malloc( ). This process is called reallocation of memory.
 With realloc(), you can allocate more bytes of memory without losing your data.

Syntax:

ptr = realloc(ptr,newsize)

Prototype:

void* realloc(void *ptr,size_t size);

Ex:

ptr = (int*)realloc(ptr,10)

 realloc( ) returns base adreess of the array or structure after decrease or increase memory.

Example:

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int main()

char *str;

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 46


PSTC UNIT-V POINTERS

str=(char*)calloc(5,sizeof(char));

if(str==NULL)

printf("memory could not be allocated");

exit(1);
OUTPUT:
} Before realloc():
String=Hello
strcpy(str,"Hi"); String size is modified
Checking the previous data exists or not
printf("Before realloc():\n”); String=Hello
Append new string to previous String
printf("\n String=%s",str);
String=Hello students
str=(char*)realloc(str,10);
Explanation :
if(str==NULL) 1) ptr=(int*)calloc(5,sizeof(char))

{
h i \0 \0 \0
printf("memory could not be allocated");
String =Hi
exit(1);
2) ptr=(int*)realloc(ptr,10)
}

printf("\n String size is modified");


H i s t u d e n t s \0
printf("\n Checking the previous data
String =Hi students
exists or not");

printf("\n String=%s",str);

printf("\n Append new string to previous

String");

strcat(str," students");

printf("\n String=%s",str);

free(str);

return 0; }

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 47


PSTC UNIT-V POINTERS

4.free( ):
 Releasing the used space or de-allocate the memory
 When a variable is allocated space, then the memory used by that variable is
automatically released by the system.
 But when we dynamically allocate memory then it is our responsibility to release
space when it is not required.
 This is more important when the storage space is limited.

Syntax : free(ptr)

 When ptr is a pointer that has been created by using malloc() or calloc(),where
memory is de-allocated using the free( ).

5.17 Some other Pointer types : (Types of pointers)


 The following are the types of the pointers.
1. Null pointer
2. Generic pointer
3. Dangling pointers
4. Wild pointer
5. Memory leakage.
 We are already discussed null pointers and generic pointer in previous, now we
will discuss the remaining three.

Dangling Pointers:

 Dangling pointers arise when memory is deleted or de-allocated, without


modifying the value of pointer, so that the pointer still points to the memory
location of de-allocated memory.
 In other word, pointer pointing to non-existing memory location is called dangling
pointer.
 Dangling pointer occurs in 3 places in our program.
i. De-allocation of memory
ii. Function call
iii. Out of scope

The following table shows the all three types of the above

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 48


PSTC UNIT-V POINTERS

De-allocation of memory Function call Out of scope

Ex: Ex: Ex:


int a=10 int *fun( ) main( )
int *ptr1; { {
int *ptr2; int x=5; char *ptr;
ptr1=&a; return &x; ptr=NULL:
ptr2=ptr1; } {
delete ptr1; Char x=’R’;
main( ) ptr=&x;
*ptr2=24;// dangling pointer { }
int *p;
p=fun( ); *ptr=’S’;// Dangling
 ptr1 holds the address of a. *p=13; // Dangling pointer
 ptr2=ptr1 then ptr2 also points pointer
to the address of a.
 When we delete ptr1, ptr2 still  fun( ) function  In above ex ptr
points to the de-allocated returns the holds the null
memory is known as dangling address of x to pointer.
pointer. main (). The  In block we
 Here we update *ptr2=24 then returned address initialized with
it rises dangling pointer stored in pointer char address into
because that memory is already variable p. when ptr.
de-allocated. we access the  Outside the block
that particular we are trying to
adreess that update the value
adreess is in address
already de- *ptr=’S’ then
allocated here occurs
because fun dangling pointer
function because when we
execution is close the block
completed then that block
the function is variables(local to
de-allocated particular block)
from memory, de-allocated from
still pointer memory. Still we
variable points are trying to
de-allocated update the value
memory. into de-allocated
memory.

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 49


PSTC UNIT-V POINTERS

Wild Pointers:

 A pointer which has not been initialized to any address (not even NULL) is known as
wild pointers.
 If we not initialized any address to pointer then it takes garbage value that is known as
wild pointer.
Ex:
int main()
{
int *ptr; // not initialized with any address .then it takes garbage val, So it a wild pointer.
int x=10;
}

Memory leakage:

 Memory leak occurs when programmer create a memory in heap memory and forget to
delete it.
 We know that, when we are creating memory using dynamic memory allocation
functions then memory allocated in heap memory. After completion of our program, to
de-allocate memory from heap then we are call free() function end the end of program.
 Memory leak is serious issue when a program is repeatedly requesting more memory and
not freeing up. They will exhaust pool of available memory.

Ex:

void arr(int n )

int *p;
p= (int *)malloc(n*sizeof(int));
----------------------
----------------------
----------------------

free(p); To avoid memory leakage we put free function at the end of the program.
}

void main( )

arr(10);

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 50


PSTC UNIT-V POINTERS

arr(15);

------------

------------

arr(100);

Heap Memory Heap Memory

10 bytes 10 bytes

15 bytes 15 bytes
---------------------- ----------------------
---------------------- ----------------------
---------------------- ----------------------

100 bytes 100 bytes


-------------------------- --------------------------
------------------------------ ------------------------------
Memory full

Fig : Without using free( ) Fig: With using free ( )

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 51


PSTC UNIT-V POINTERS

 Without using free() in function or program using dynamic memory allocation when we
are call the function again and again the memory full at some point, then occurs the
memory leakage problem.
 To overcome this problem we put free( ) at the end of the function then every completion
of a function execution de-allocates its memory by free ( ) function.

5.18 Command Line Arguments :


 Command line arguments are given after the name of a program in command line
operating system like DOS or linux, and passed in to the program from the operating
system.
 Till now, no arguments were passed in to the main( ).But now in order to understand
command-line arguments. The main() accept two arguments

int main( int argc,char *argv[ ])


 The first argument is argc, it counts the number of arguments passed to the program
include program name. here program name is a first argument. If we not pass any
arguments then the argument count is 1 because it counts program name.
 The second argument argv[ ], it contains list of all elements argv[0] is the name of the
program, or empty string if the program name is not available.
 argv[1] to argv[argc-1] specifies the command line arguments. Every elements in argv
can be used as string.
 Note: if we are access the nth element or argv[argc] prints null pointer.
 All elements in argv[ ] are string type. argv[ ] stores the address of the command line
values.

Steps to run program in Cmd:

1. Open notepad (editor) to write a program.


2. Open cmd and locate compiler
3. Compile source program.
4. Run program.

Example 1:
Output on cmd: (turbo c)
#include<stdio.h>
>tcc program.c // compile
int main(int argc,char *argv[ ] )
>program //run
{
argument count:1
Printf(“arguments count:%d”,argc);

Example 2:

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 52


PSTC UNIT-V POINTERS

#include<stdio.h>

int main(int argc,char *argv[ ] )

int i=0;

if(argc==1){

printf(“No elements to display…”);

else {

printf(“List of elements:\n”);

for(i=1;i<agrc;i++)

printf(“%s\n”,argv[i]);

To compile & run the above program (using different compilers)

OUTPUT:

In turbo c: In linux: In devc++:

Cmd cmd Cmd

>C:/tcc.exe prgm.c > . / a.out ‘R’ 24 2.7 > F: program.exe ‘R’ 24 2.7

>C:/prgm ‘R’ 24 2.7 R R

R 24 24

24 2.7 2.7

2.7

 In devc++, first we
compile the program in

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 53


PSTC UNIT-V POINTERS

devc++ IDE then run


the program on cmd.

Note:

 Command line argument always string type . when we are using addition of two numbers
then it is not possible in string type. so we need to convert argument from string to int.
 To solve this program dos.h library provides two functions:
1. atoi ( ) function.
2. atof( ) function.
 These two functions included in dos.h library. To use these function we include dos.h
library.
 atoi( ) function converts command line arguments string type to integer type.
 atof( ) function converts command line arguments string type to float type.

Example 3: ( to add two numbers using command line arguments) :

#include<stdio.h>

#include<dos.h>

int main(int argc,char *argv[])

if(argc>2)

char* s1=argv[1];

char* s2=argv[2];

int x=atoi(s1);

int y=atoi(s2);

printf("sum:%d\n",x+y);

else

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 54


PSTC UNIT-V POINTERS

printf("insufficient input values to add numbers we need more than 1


value ");

return 0;

OUTPUT: ( using Devc++)

 If we pass more than two arguments its takes only first two values reaming are omits.

Memory allocation of command line arguments:

 We know that, In command line arguments main() function takes two arguments i.e argc
and argv[].
 When we pass the arguments through command line, argv[] is can stores the address of
string type.
 Command line arguments always string type. all the strings arguments stored in different
locations. argv[] holds the address of the all the arguments where it stores.
 Here program name is a first argument it store in argv[0]
 To understand memory allocation of command line arguments observe the following
figure.

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 55


PSTC UNIT-V POINTERS

Fig: Memory allocation of command line arguments

 In the above program , we passed four arguments but total arguments are five because
program name is a 1st argument.
 When we trying to access argv[argc] or argv[5] then prints NULL string.

****ALL THE BEST FOR UR EXAMS****

M.Ramesh , Dept of CSE, IIIT-Nuzivid. Page 56

You might also like