Pointer
Pointer
-----------------------------------------------------------------------------------
------------------------------
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.
-----------------------------------------------------------------------------------
---------------
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;
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;
int x=10;
int *p;
p=&x;
-----------------------------------------------------------------------------------
---------------
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.
if p1 and p2 are both pointer to the same array, then p2-p1 gives the
number
of element between p1 and p2.
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
int A[10] = 5 7 11 54 34 65
76 8 23 76 value
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));
}
-----------------------------------------------------------------------------------
-----------------------------------------
//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.
Syntax
ptr = (cast_type *) malloc( byte -size);
Allocate space for an array of elements, initialize them to zero and then return
a pointer to the memory.
-----------------------------------------------------------------------------------
-----------------------------------
-----------------------------------------------------------------------------------
------------------------
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.
-----------------------------------------------------------------------------------
------------------------------------
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()
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);
-----------------------------------------------------------------------------------
----------------
//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);
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];
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.
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.
Constant Pointer :
Constant pointer cannot be changed that means address within a computer.
-----------------------------------------------------------------------------------
-----------------------------------------------------
Types of Pointer.
ii) Dangling pointer. : A pointer pointing to memory location, that has been
deleted, or freed
is called dangling pointer.
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.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
#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++;
return 0;
}
output = 21, 1000, 1004;
--------------------------------------------------------------