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

Pointer

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Pointer

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

chapter Pointer

Pointer is derived datatype.


Pointer is variable which store address of another variables.
Pointer contains memory addresses as their values. Since these memory address
are the location in the computer memory. where the program instruction and
data are stored.
Pointer can be used to access and manipulate data stored in the memory.

-----------------------------------------------------------------------------------
------------------------------
Need of Pointers
i) It enhances the capability of the language of manipulate data.
ii) Pointers reduce the length and complexity of the program.
iii) It is used for creating data structures such as Linked List, trees, graphs,
stack, queue and so on.
iv) Use of Pointer to access array of Strings saves the data storage space in
the memory.
v) Pointer is used to pass information to and from the functions.
vi) It allows working with dynamically allocated memory.
vii) It inecreases the execution speed.

-----------------------------------------------------------------------------------
-------------------------------------
Concept of Pointer
int a = 10; // it allocate memory in computer,
Every data element in the computer is stored in memory in one or more
adjcent location
depending upon its type. Computer memory is sequencial collection of storage
cell.
Each cell is known as byte. and it has a number is called address.
The addresses are named in a serial manner, starting from zero.
Suppose computer system having 1KB memory will be 0 to 1023 is last address.

int x=20;
The variable x is associated with address 1000. since memory
address are just numbers,
they are also assigned to any variable that can be stored in memory location.
such variables that contain the memory address are called pointer.

Access the Address of a Variable.


The actual location of variables in the memory is system dependent and
therefore the address of
variable is not known immdiately.
If u want known address of variable we use '&' (amparsand) opearator.
'&' operator given Address of variable.

-----------------------------------------------------------------------------------
---------------
Features of Pointer
i) pointer variable should have prefix '*'.
ii) Combination of data type is not allowed.
iii) Pointer are more effiective and useful in handling arrays.
iv) It can also be used to return multiple values from a function using pointer
args.
v) It Support Dyamic Memory Allocation (DMA).
vi) It reduces complexity and length of a program.
vii) It helps to improve execution speed.
viii) Pointer provide an alternate way to access individual array elements.
-----------------------------------------------------------------------------------
---------------
//WAP to print address of a variable along with its values.
#include<stdio.h>
#include<conio.h>
int main()
{
char ch;
int x;
float p,q;

ch='A';
x=125;
p=12.45;
q=23.53;

printf("\n %c is stored at address =%u ",ch, &ch);


printf("\n %d is stored at address =%u ", x, &x);
printf("\n %0.2f is stored at address =%u ", p, &p);
printf("\n %0.2f is stored at address =%u ", q, &q);

return 0;
}

-----------------------------------------------------------------------------------
------
Declaring Pointer Vapriables.
In C, Every variable must be declared for it datatype. Since pointer variables
contains
addresses that belong to a separate data type. They must be declared as pointer
before we use them.
Syntax
datatype *ptrvar; ( '*' is asterisk )
e.g
int *p;
float *x;
double *q;

Accessing the value of variable through pointer by using '*' operator.

int x=10;
int *p;
p=&x;

The value represent by x, can be accessed by the expression *p.


where * is called 'value at the address' operator and it is unary
operator.

x is represent the value 10;


and *p is also represent the value 10;
Accessing to an object through pointer is called de-referencing
and asterisk(*) operator is called de-referencing or indirection operator.

-----------------------------------------------------------------------------------
---------------
Pointer Initilazation
The process of assigning the address of a variable to the pointer is called
initialization.
All uninitialization pointer will have some unknown values that will be
interpreated
as memory addresses.
After declaration, we have to initialize the pointer variable. Use of the
addressof (&) operator
as a prefix to the variable name assign its address of the pointer.

e.g int a=5, x, *ptr;


ptr = &a;
x=*ptr;
-----------------------------------------------------------------------------------
---
#include<stdio.h>
#include<conio.h>
int main()
{
int x,y;
int *ptr;
x=10;
ptr=&x;
y=*ptr;
printf("\n value of x->%d",x);
printf("\n %d is stored at address=%u",x,&x);
printf("\n %d is stored at address=%u", *&x,&x);
printf("\n %u is stored at address=%u", ptr,&ptr);
printf("\n %d is stored at address=%u", y,&y);
printf("\n %d is stored at address=%u", *ptr,&ptr);
printf("\n %d is stored at address=%u", y,&x);
printf("\n %d is stored at address=%u", *&*&x,ptr);
*ptr=50;
printf("\n value of x->%d",x);
printf("\n %d is stored at address=%u",x,&x);
return 0;
}
-----------------------------------------------------------------------------------
--
Chain of Pointers
One Pointer point to second pointer, Second pointer point to third pointer,
Third pointer point to Fourth pointer, and so on, is called chain pointers.
This is known as Multiple indirection.
A variable that is a pointer to a pointer must be declared using additional
indirection
operator symbol.
--------------------------------------------------
#include<stdio.h>
#include<conio.h>
int main()
{
int x,*p1,**p2, ***p3;
x=11;
p1=&x;
p2=&p1;
p3=&p2;
printf("\n value of x is -->%d",x);
printf("\n value of -->%d",*p1);
printf("\n value of -->%d",**p2);
printf("\n value of -->%d",***p3);
printf("\n value of -->%d", ***&p2);
printf("\n value of -->%d",**&*&p1);
return 0;
}
-----------------------------------------------------------------------------
Pointer Arithmetic.
Like other variables, pointer can be used in arithmetic expression.
e.g if p1 and p2 are properly declared and initialized pointers.
then following statement are valid.

y= *p1 * *p2; // y=(*p1) * (*p2);


sum = sum + (*p2);
z= 5 * - *p2 / *p1; // z= 5 * (-(*p2)/(*p1))
*p2 = *p2 + 10;

C lang allow us to add integer or subtract integer from pointers. as well


as
to subtract one pointer from another.

p1+4, p2-2, and p2-p1 are all allowed.

if p1 and p2 are both pointer to the same array, then p2-p1 gives the
number
of element between p1 and p2.

we may also short hand operator with the pointer.


a=a+b ===> a+=b;
a=a-b ===> a-=b;
x=x*y ===> x *=y;
x/=y => x=x/y; p%=10 ===> p= p%10;

*p1= *p1+10 ==> *p1 + =10;

*p1 - = *p2 ===> *p1 = *p1 - *p2;

*p1++, p1++; --p2;

we can compare pointer using relational operator.


p1 > p2; p1==p2, p1 != p2; p1 < p2;

But we cannot use pointer in division and multiplication


p1 / p2; p1 * p2; or p1 / 3; (Not Allowed)

// WAP to use of arithmetic operation on Pointer.


#include<stdio.h>
#include<conio.h>
int main()
{
int a,b, *p1,*p2, x,y,z;
a=12;
b=4;
p1=&a;
p2=&b;

x=*p1 * *p2 -6;


y=4 * - *p2 / *p1 + 10;
printf("\n Address of a= %u and b=%u",p1,p2);

printf("\n value of a=%d and b=%d ",a,b);


printf("\n value of x=%d and y=%d ",x,y);
*p2 = *p2 +3;
*p1 = *p2 -5;
z = *p1 * *p2 - 6;
printf("\n value of a=%d and b=%d ",a,b);
printf("\n value of z=%d",z);
return 0;
}
---------------------------------------------------------
Pointer Increament and scale factor.
#include<stdio.h>
#include<conio.h>
int main()
{
char ch='A' , *cp;
int x=10,i, *p1;
float y=4.56, *p2;
long z=100, *p3;

cp=&ch; p1=&x; p2=&y; p3=&z;


printf("\n Char \t\t int \t\t float \t\t long \n");
printf("\n %u \t %u \t %u \t %u",cp, p1,p2,p3);

for(i=0;i<3;i++)
{
cp++; p1++; p2++; p3++;
printf("\n %u \t %u \t %u \t %u",cp, p1,p2,p3);
}
printf("\n ============================================================\n") ;
for(i=0;i<3;i++)
{
cp--; p1--; p2--; p3--;
printf("\n %u \t %u \t %u \t %u",cp, p1,p2,p3);
}
printf("\n ============================================================\n") ;
printf("\n %u \t %u \t %u \t %u",cp+4, p1+6,p2+3,p3+8);
return 0;
}
----------------------------------------------------------------------------
#include<stdio.h>
int main()
{
int a,b;
int c=3;
int *p;
a=2*(c+5);
p=&c;
b=2*(*p+5);
printf("\n value of a=%d and b=%d",a,b);

return 0;
}

-----------------------------------------------------------------------------------
-----------------------------------------------------
Rules of Pointer operation
i) A pointer variable can be assigned the address of another variables.
ii) A pointer variable can be assigned the value of another pointer
variables.
iii) A Pointer variable can be initialized with NULL or Zero value.
iv) A pointer variables can be prefixed or postfixed with increment or
decrements operators.
v) An Integer value may be added or subtracted from a pointer variable.
vi) When two pointer point to the same array, one pointer variable can
be subtracted from another.
vii) When two pointer point the object of the same data types, they can
be compared using relational operators.
viii) A pointer variable cannot be multiplied or divided by a constant.
ix) Two pointer variables cannot be added.
x) A value cannot be assigned to an arbitrary address (i.e &x=10; is
illegal).

-----------------------------------------------------------------------------------
-------------------------------------------------------
Pointers and array.
when an array is declared, the compiler allocate a base address and sufficient

Amount of strorage to contains all the element of the array in contiguous


memory location.
base address is the location of the first elements.
0 1 2 3 4
5 6 7 8 9 variable

int A[10] = 5 7 11 54 34 65
76 8 23 76 value

1000 1002 1004 1006 1008 1010


1012 1014 1016 1018 address.

now if we declare p as an integer pointer. and pointer 'p' point to


array 'A'
int *p;
p=A; // array assign to pointer p.
p = &A[0] = 1000;
p+1 = &A[1] = 1002;
p+2 = &A[2] = 1004;
p+3 = &A[3] = 1006;
|
|
p+9 =&A[9] = 1018
------------------------------------------------------------------
//WAP to print address of array of pointer.
#include<stdio.h>
int main()
{
int i,a[5]={11,22,33,44,55};
int *p;
p=a;
for(i=0;i<5;i++)
{
printf("\n value of a[%d] = %d and address=%u",i,*p,p);
p++;
}
return 0;
}
-------------------------------------------------------------------------
//WAP to print address of array of pointer.
#include<stdio.h>
int main()
{
int i,a[5]={11,22,33,44,55};
int *p;
p=a;
for(i=0;i<5;i++)
{
printf("\n value of a[%d] = %d and address=%u",i,*(p+i),(p+i));
}
return 0;
}
--------------------------------------------------------------------------
//WAP to print address of array of pointer.
#include<stdio.h>
int main()
{
int i,a[5]={11,22,33,44,55};

for(i=0;i <5;i++)
{
printf("\n value of a[%d] = %d and address=%u",i,a[i],&a[i]);
}
return 0;
}

-----------------------------------------------------------------------------------
--------
//Display Array elements in Reverse order by using pointer
#include<stdio.h>
int main()
{
int i,a[5]={11,22,33,44,55};
int *p;
p=a;
for(i=0;i<5;i++)
{
printf("\n value of a[%d] = %d and address=%u",i,*(p+i),(p+i));
}

printf("\n Display Array element by using pointer\n");


for(i=4;i>=0;i--)
{
printf("\n value of a[%d] = %d and address=%u",i,*(p+i),(p+i));
}
return 0;
}

-----------------------------------------------------------------------------------
-----------------------------------------
//WAP to using pointer to compute the sum of all elements stored in an array.
#include<stdio.h> // x[0] x[1] x[2] x[3] x[4]
#include<conio.h> // 10 20 30 40 50
int main() //1000 1002 1004 1006 1005
{
int *p, sum=0, i;
int x[5]= {10,20,30,40,50};
p=x;
printf("\nElement Value Address");
for(i=0;i<5;i++)
{
printf("\n X[%d] \t %d \t %u ",i,*p, p);
sum = sum + *p;
p++;
}
printf("\n Sum of array element =%d",sum);
printf("\n First address =%u and last address =%u",&x[0], p);
return 0;
}
-----------------------------------------------------------------------------------
-----------------------
Dynamic Memory Allocation (DMA).
The process of allocating memory at run time is known as Dynamic Memory
allocation.
In static allocation, the memory get reserved for the variables at compile time.
In many cases, we
donot know the amount of memory which may need beforehand. hence memory may be
wastage
or shortage in static allocation. i.e (in array)
For this problem, C provide dynamic memory allocation, which allocating
and freeing memory
during runtime. this results in a more efficient utilization of memory. and
protect from wastage.

C Library provide three function for allocation (malloc, calloc, and


realloc).
freeing function is ( free() ) this function are stored in
<stdlib.h> library file.

malloc() : A block of memory may be allocating using the function malloc().


The malloc() function reserve a block of memory of specified
size.
Allocate request size of bytes and return a pointer to first
byte of the allocated space.
malloc or memory allocation method in C is used to
dynamically alloacate a single large
block of memory with the specified size. It return a pointer
of type void. which can be
cast into a pointer to any form. It Doesnot initialize
memory at execution time so that
it has initialized each block with the default garbage value
initially.

Syntax
ptr = (cast_type *) malloc( byte -size);

e.g int *p;

p=(int *)malloc(sizeof(int)); //single block allocate


karnar

p=(int *) malloc(10 * sizeof(int)); // it reserves a


block of memory size of 10.

char *x =(char *) malloc(30* sizeof(char)); // it reserves a


block of memory size of 30 char.
-----------------------------------------------------------------------------------
-----------------
calloc() : calloc is another memory allocation function that is normally used
for requesting memory
space at run time for storing derived data types such as array and
structures.
while malloc allocate a single block of storage space. calloc
allocates multiple blocks of storage.
each block have same size, and then sets all bytes to zero.

Syntax ptr = (cast_type *) calloc(n, element -


size);

e.g int *p;


p=(int *)calloc(10, sizeof(int)); //
allocate 10 block by using calloc

Allocate space for an array of elements, initialize them to zero and then return
a pointer to the memory.

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

realloc() : Modifies the size of previously allocated space.


suppose allocated memory is not sufficient or allocated memory is too
large than necessary.
at that time we want to increased or reduce memory according to user
requirements,
the we use realloc() function.
It allocate new memory size of 'newsize' to the pointer variable ptr
and returns the pointer
to the first byte of the new memory block.

ptr= malloc(size); // suppose ptr exiting memory, want to


modify
ptr=realloc(ptr, newsize);
e.g
ptr= realloc(ptr, 10);

-----------------------------------------------------------------------------------
------------------------
free() : when we no longer need the data or data storage is not required for
longer time. then
we freeze that memory location by using free() function.

e.g Syntax free(ptr);


e.g free(p);

-----------------------------------------------------------------------------------
------------------------------------
Advantage of Dynamic Memory allocation over static memory allocation.
i) Allocates memory at run time.
ii) Neither wastage nor shortage of memory space
iii) It can either grow or shrink during the execution of the program.
iv) Data can be rearranged efficiently through DMA.
v) Speed of DMA is faster than static allocation.
vi) Freeing of unnecessary memory is possible through DMA.

-----------------------------------------------------------------------------------
-----------------------------
01-04-2021
Difference between malloc() and calloc()

i) the malloc() requirees one arguments i.e total no of bytes to be allocated.


the calloc() requires two arguements- the number of objects and size of each
object.

ii) Memory allocated by malloc() contains garbage values . i.e malloc doesnot
initialize the memory
whereas calloc() initialize the memory to 0.
-----------------------------------------------------------------------------------
------

//WAP to allocate memory for pointer var, stored values and display
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr,n,i;
printf("\n How many numbers u want :->");
scanf("%d",&n);

ptr=(int *) malloc(n*sizeof(int));
printf("Enter the number :->");
for(i=0; i<n;i++)
scanf("%d", ptr+i);

printf("Display the number :->");


for(i=0; i<n;i++)
printf("%4d",*( ptr+i));
return 0;
}

-----------------------------------------------------------------------------------
----------------
//WAP to demonstrate of allocation and deallocation. display sum of all element
by using pointer. an also element is reverse of order.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr,n,i,sum=0;
printf("\n How many element u want:->");
scanf("%d",&n);

ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL)
{
printf("\n Memory not allocated..");
exit(0);
}
printf("\n Enter the elements :->");
for(i=0;i<n;i++)
{
scanf("%d",ptr+i);
sum =sum+*(ptr+i);
}
printf("\n Display the elements :->");
for(i=0;i<n;i++)
{
printf("%4d",*(ptr+i));
}
printf("\n Sum of elements ->%d",sum);

printf("\n Display elements in reverse order :->");


for(i=n-1;i>=0;i--)
{
printf("%4d",*(ptr+i));
}
printf("\n Sum of elements ->%d",sum);

free(ptr);
return 0;
}
-----------------------------------------------------------------------------------
----------------------------------
Memory allocation for a matrix of 'r' rows and 'c' columns can be done in two
ways.
i) Allocate a single block to whole r*c elements. Here we requires a single
pointer to point to the block.
ii) Allocate memory row-wise i.e allocate memory for each row separately. In such
case,
we will get 'r' different addresses for the 'r' rows
hence we can use array of pointer. each address in this array points to a row
of 'c' elements.
char *x[5];

//WAP to accept String array by using pointer.


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *row[6], name[40];
int i,l;
for(i=0;i<6;i++)
{
printf("\n Enter the name :->");
gets(name);
row[i]=(char*)malloc(strlen(name));
strcpy(row[i],name);
}
printf("\n Display name :->\n") ;
for(i=0;i<6;i++)
puts(row[i]);
return 0;
}

row[0] contains address of '0' elements. any elements of this matrix, can be
access by specifies
the row address and offset.
the address of the (i,j)th element will be row[i]+j;
the value of the (i,j)th element will be *(row[i]+j);
-----------------------------------------------------------------------------------
---------------------
Differenc between Static and Dynamic memory allocation.
Static memory allocation.
Dynamic memory allocation.
i) It allocate memory at compile time. i) It
allocate memory at runtime (execution) time.
ii) allocate memory size remains fixed ii) allocate
memory cannot be fixed, its allocate

or deallocate dynamically
iii) variable remains permanently allocated. iii) allocate only
when program unit is activated.
iv) faster execution than dynamic. iv) slower
execution than static.
v) more memory space required. v) Optimum
usage of memory space.
vi) Data is stored in data segments in memory vi) Data is stored in
heap memory.

-----------------------------------------------------------------------------------
----------------------------------------------------------------------
Memory leaks.
memory leaks occures when there is dynamically allocated memory area. in a
heap but no pointer
variables pointing to that memory. a memory leaks is memory which has not
been freed and
there is no way to access or free it. This usually happen when a pointer
which was only reference to dynamically allocated memory location.
points somewhere else now.

int *ptr1= (int *)malloc(10);


int *ptr2= (int *)malloc(20);
ptr1 = ptr2;
here, the first block 10 byte doesnot have any pointer pointing to it
anymore,
hence it is memory leak.

Dangling Pointer.
when there is pointer variable which hold the address of a memory block, but
there no memory
in heap, the pointer is a dangling pointer. Dangling pointer is the reverse
of memory leak.
when u free of area of memory but still keep pointer to it that pointer is
dangling.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr=(int *)malloc(10);
printf("\n Address =%u",ptr);
free(ptr);
printf("\n Address =%u",ptr);
ptr=NULL;
printf("\n Address =%u",ptr);
return 0;
}
-------------------------------------------------------------------------
Void pointer
It is a generic type that is not associated with a reference type. that is,
it is not the address of a character an integer, a real, or any other type.

Declaration of void pointer


void *ptr;
note that , void pointer cannot be dereferanced, this is the major
difference between
void pointer and NULL Pointer. Null pointer are assigned to constant
Null.

Constant Pointer :
Constant pointer cannot be changed that means address within a computer.

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

Types of Pointer.

i) Null Pointer : NULL is pointer, which is pointing to nothing. usually


pointer are initialize
in the beginning to null. It's indicate that
it doesnot having any valid address.

ii) Dangling pointer. : A pointer pointing to memory location, that has been
deleted, or freed
is called dangling pointer.

iii) Generic pointer : When a pointer is declared as type void, it is known as


generic pointer.
this pointer cannot used directly.

iv) Wild Pointer : A pointer which has not been initilize to anything. not
even NULL. Wild pointer
points to some random memory location

v) Near pointer : Near pointer can stored a 16 bit address. which can point
to only 64 kb data.
data segments or segments number is known as
near pointer.

vi) Far pointer : A pointer which can point or access the whole memory of
ram. i.e
all 16 segments is known as far pointer. size
of far pointer is 4 bytes or 32 bits.

vii) Huge poiner : A pointer which can pointer or access whole residence memory
of ram. i.e
which can access all 16 segments is known as
huges pointer.

viii ) Complex pointer : multilevel pointer, pointer to function, pointer to


array of function,
pointer to multidimensional array, pointer
nested in structure. or union,
etc. are complex pointer.

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
#include<stdio.h>
int main()
{
int a[]={1,2,3,4,5};
int *p;
p=a;
printf("%d",*(p+1));
return 0;
}
o/p=2;
-----------------------------------------
#include<stdio.h>
int main()
{
int i=6,*j,k;
j=&i;
printf("%d\n", i * *j * i + *j);
return 0;
}
output =222
-----------------------------------------------------
#include<stdio.h>
int main()
{
int x=20,*y,*z; // consider address=1000
y=&x;
z=y;
*z++;
x++;

printf("\n x=%d \n y=%d,\n z=%d",x,y,z);

return 0;
}
output = 21, 1000, 1004;
--------------------------------------------------------------

You might also like