pointer applications to understand the relationship between arrays and pointers. to understand the...

41
Pointer applications • To understand the relationship between arrays and pointers. • To understand the design and concepts behind pointer arithmatic. • To write programs using arrays and pointer arithmetic. • To understand passing arrays to functions. • To understand dynamic memory allocation. • To write programs using static and dynamic memory allocation.

Upload: pearl-west

Post on 16-Dec-2015

234 views

Category:

Documents


3 download

TRANSCRIPT

Pointer applications

• To understand the relationship between arrays and pointers.

• To understand the design and concepts behind pointer arithmatic.

• To write programs using arrays and pointer arithmetic.

• To understand passing arrays to functions.• To understand dynamic memory allocation.• To write programs using static and dynamic

memory allocation.

Pointer Applications Arrays and pointers:• Arrays and pointers have close relationship.• Array is a collection of similar elements stored in

contigous memory locations. Hence pointers can be easily applied on arrays.

void main(){

int a[5]={1,2,3,4,5};int i=0;while(i<5){

printf(address of element %d is %p”,i, &a[i]);}

}

Pointer applications

• The name of an array is the pointer constant to the first element.

• int a[]={1,2,3,4}; a and &a[0] both are same• We can use the array name anywhere we use

the pointer as long as it is being used as an rvalue.

• printf(“%p %p”,&a[0],a);

Pointer applications

• Printing first element *a same as a[0]• Store a in a pointer variableint a[4]={1,2,3,4};int *p=a;printf(“%d%d”,*p,*a);• Multiple pointer to arraysint a[3]={1,2,3}; int *p=&a[1];printf(“%d %d %d”,a[0],p[-1],p[0]);

Pointer arithmetic and arrays

• a is a pointer to a[0]• a+1 is a pointer to a[1]• a+2 is a pointer to a[2] and so on• Address=pointer+offset*size of element• Pointer arithmetic on different types• Dereferencing array pointers a[2] is same as

*(a+2)

Two methods to access the elements of array:

1.using subscript.

2.Using pointers.

Subscript method:void main(){

int a[5]={1,2,3,4,5};int i=0;while(i<5){

printf(address of element %d is %p”,a[i], &a[i]);

i++;}

}

Pointer method:• Pointers can be made to point to the array and then

used to access the elements.• Efficient method in complex situations.Main(){

int a[3]={1,2,3};int *ptr;int i=0;ptr=&a[0];while(i<3){

printf(element is %d , *ptr);ptr++;i++;

}}

Base address of an array:• Starting address of an array.• Represented by the ‘&array_name[0]’(ex:&a[0]).• Can also represented by just specifying the array

name.(ex:a)int a[3];int *ptr;ptr=&a[0]; //also ptr=a;• Here if array starts at address 2000, then ptr will have

value 2000.• Since array name gives its starting address, *a gives

the first element of the array. • Pointers can also be used array name and index it to

point to different elements in the array.print(ptr[0]); //prints first element of array aprint(ptr[2]); //prints 3rd element of a

Pointer arithmetic and arrays:Pointers pointing to array can be 1.Incremented or decremented.2.An integer can be added to pointer.3.An integer can be subtracted from the pointer.4.Two pointers pointing to the same array can be subtracted.5. Pointers can be compared using relational operators(array)void main(){

int a[3]={1,2,3};int *ptr;int i=0;ptr=a;while(i<3){

printf(element is %d , *ptr);ptr++;i++;

}}

o/p:1 2 3

void main(){

int a[3]={1,2,3};int *ptr;int i=3;ptr=&a[2]; //ptr=a+2; while(i>=0){

printf(element is %d , *ptr);ptr--;i--;

}}

o/p: 3 2 1

Main(){

int a[7]={1,2,3,4,5,6,7};int *ptr;ptr=a;printf(“element at zero position is %d” , *ptr); //1ptr=ptr+3;printf(“element at 3rd position is %d” , *ptr); //4ptr=ptr+2;printf(“element at 5th position is %d” , *ptr);//6ptr=ptr-3;printf(“element at 2nd position is %d” , *ptr); //3

}

1 2 3 4 5 6 7

2000 2002 2004 2006 2008 2010 2012

• Array name can also be used to increment or decrement.

int a[4]={1,2,3,4};

print(*a); //1

print(*(a+1)); //2

print(*(a+3)); //4• Addition of 2 pointers is not allowed but subtraction is

possible only if the pointers points to the same array.• Subtraction of 2 pointers gives the number of elements

between 2 pointers.

int a[4]={1,2,3,4};

int *ptr1,*ptr2;

ptr1=a;

ptr2=&a[2]; //or ptr2=a+2

k=ptr2-ptr1; //2

Find the smallest in an array• #define SIZE 10• void main()• {• int a[SIZE]={21,31,4,51,63,78,80,19,10,11};• int *psm,*plast,*pwalk;• plast=a+SIZE-1;• psm=a; pwalk=a+1;• while(pwalk<=plast) {• If (*psm>*pwalk) psm=pwalk; pwalk++;• }

Binary search

• int bsearch(int list[],int *endp,int target,int **locp)• { int *fp,*mp,*lp;• fp=list; lp=endp;• while(fp<=lp)• {• mp=fp+(lp-fp)/2;• if(target>*mp) fp=mp+1;• else if(target<*mp) lp=mp-1;

Binary search

• else break;• }• *locp=mp;• return (target==*mp);}• void main()• {• int list[10]={12,34,56,64,68,70,79,88,99,100};• int found,int *pos=NULL; int key;

Binary search

• printf(“Enter key”);• scanf(“%d”,&key);• found=bsearch(list,list+9,key,&pos);• If(found) printf(“Key is found and its position is

%d”, *pos);• else printf(“key is not found”);• }•

Pointers and 2D-arrays• 2D array is an array of 1D arrays.• A[2][3]; is nothing but two 1D arrays of 3 elements each.

a[2][3]={1,2,3,4,5,6}; will be stored in memory locations as shown below

• a[0] gives the base address of 0th 1D array and a[1] gives the base address of 1st first 1D array. hence a[0]2000 and a[1]2006

1 42 53 6

2000 2002 2004 2006 2008 2010

a[1]

a[0]

• In 1D array ‘*’ prefixed with array name gives the element at that position in array.i.e *a1 //also *(a+0) *(a+1)2 etc

• Since 2D arrays are collection of 1D arrays ,‘*’ prefixed with 2D array name gives the base address of 1D array.a[2][3];*(a+0)2000*(a+1)2006

How to refer to individual elements of 2D array using pointers?for ex: how is a[1][2] element represented using pointers.a[1] is represented as *(a+1).Now , a[1][2] is nothing but the 3rd element of the row that we reached in the previous step. hence it can be represented as *(*(a+1)+2)

a[2][3]={1,2,3,4,5,6};

*(a+0)

*(a+1)

*(a+1)+2

*(*(a+1)+2)6

Hence element a[2][1] can be written as *(*(a+2)+1);

and a[1][1] as *(*(a+1)+1) and so on.

In general element a[i][j] can be written as *(*(a+i)+j);

1 2 3

4 5 6

Passing array to functions:

Array can be passed to functions by

1.Passing value of array elements.

2.Passing address of array elements to functions.

3.Passing the base address of the array.

Passing value of array elements:

Main()

{

int arr[3]={1,2,3};

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

display(arr[i]);

}

Void display(int m)

{

print(m);

}

o/p: 1 2 3• Changes not reflected in actual arguments.

Passing address of array elements:

Main()

{

int arr[3]={1,2,3};

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

display(&arr[i]);

}

Void display(int *ptr)

{

print(*ptr);

}

o/p : 1 2 3

Passing the base address:

Main()

{

int arr[3]={1,2,3};

display(arr,3);

}

Void display(int *ptr, int n)

{

int i;

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

{

printf(“%d”,*ptr); //also ptr[i]

ptr++;

}

}

o/p : 1 2 3• It is compulsory to pass the number of elements to the

function display because display function does not know the size of array.

Array of pointers:• Is nothing but an array which contains addresses.Main(){

int *arr[4]; //array of pointersint i=1,j=2,k=3,l=4;arr[0]=&i; arr[1]=&j; arr[2]=&k; arr[3]=&l;for(m=0;m<4;m++)printf(“%d”,*(arr[m]) );

}o/p: 1 2 3 4

Memory management

• Memory is divided into program memory and data memory

• Program memory memory used for functions and main

• Data memory is divided into global,stack and heap memory

• Global memory holds global data of program• Stack memory holds local variables with respect to

different activations of the functions• Heap memory is unused memory allocated to the

program and available to be assigned during program execution.

Memory allocation functions:

There are 2 types of memory allocations

1.Static allocation (inefficient)

2.Dynamic allocation(efficient)

Static allocation:• Happens during compile time.• Memory once allocated is fixed.• Results in wastage or shortage of memory.• Use of arrays is static allocation.

Main(){

int arr[50];printf(“enter the no of elements”);scanf(“%d”&n);printf(“enter employee ID’s);for(i=0;i<n;i++)scanf(“%d”, &arr[i]);

}• An array is created with capacity to hold upto 50

integers.• The size of 50 is fixed and cannot be changed.• Now if number of employees is 25, remaining 25

spaces will get wasted.• Now if you want to enter more than 50 emp ID’s,

array memory will fall short.• These are disadvantages of the static allocation . To

overcome these we use dynamic allocation.

Dynamic allocation:• Allocating memory during runtime of the program.• Memory is allocated only as much is really required,

not a byte more and not a byte less.• It is done by using pointers.• There are 3 functions in c for dynamic allocation

1.Malloc

2.Calloc

3.Realloc

One for freeing the memory allocation

1. Free

These functions are present in the header file <stdlib.h>.

malloc

• void *malloc(size_t size);• size_t is a datatype defined in stdio.h as unsigned

integer which can hold the maximum address of the computer.

• Ex: int *ptr=(int*)malloc(sizeof(int));• Returns a pointer to the first byte of a block of

memory whose size is size and contents are uninitialized.

• Returns NULL if unsuccessful.• If size==0 then result is unpredictable.

Usage

• If(ptr=(int *)malloc(sizeof(int))) exit(100);

Calloc

• Used for arrays.• Void * calloc(size_t count,size_t elementsize);• Allocates count*elementsize number of bytes

and returns start address.• Initializes block content to null char.• Returns NULL if unsuccessful• int *a=(int *)calloc(10,sizeof(int));• if(!ptr=(int*)calloc(200,sizeof(int))) exit (100);

Realloc

• Whenever allocated block needs to be extended or shrinked we use realloc.

• Void * realloc(void *ptr,size_t newsize));• If extension is not possible at old place it

allocates the block at new place ,copies contents of old place ,delets old place and returns pointer to new place.

Free

• Void free(void * ptr);• Free(NULL) free(a pointer to other than first

byte),free(different datatype ptr) not allowed.• Free(ptrname);

Main(){

int n,*ptr,i;printf(“enter the no of employees”);scanf(“%d”&n);ptr=(int *)malloc(n * Sizeof(int)); //dynamic allocationif(ptr==NULL){

printf(“insufficient memory”);exit();

}printf(“enter employee ID’s);

for(i=0;i<n;i++)scanf(“%d”, (ptr+i));

printf(“displaying emp ID’s”);for(i=0;i<n; i++)printf(“%d”, *(ptr+i));

}

Close look at

ptr=(int *) malloc (n * sizeof(int));• Here if n is 5, then 5* sizeof(int) i.e 5*2 = 10 bytes are

allocated which is exactly what is required for storing 10 employee ID’s , not a single byte less or more.

2000 2002 2004 2006 2008

ptr• Since we have to store emp ID’s which is an int, int is

specified as the parameter of sizeof() function.• Malloc function always returns a void pointer. It has to be

typecasted to int pointer since ptr is pointing to int type emp ID

• Malloc function returns a pointer which points to the first byte of the block of memory allocated.

Calloc:• It is same as malloc, but here it takes 2 parameters.

calloc (int m, int n);m indicates number of blocks. n indicates size of each block.

Ex:int *ptr;ptr=(int *) calloc (5, sizeof(int));This reserves space of 10 bytes.i.e 5 blocks of size 2

each.

Realloc:• Used to change the size of memory already allocated ,

using malloc or calloc.• It is rarely used.

• If sufficient amount of memory is not there, malloc returns NULL.

• (ptr+i) in scanf specifies the address where ID is to be stored.

2000 2002 2004 2006 2008

Ptr

Ptr+1

Ptr+2

ptr=(int *) realloc (ptr, 10 * sizeof(int));• Initially ptr was pointing to a block of bytes(10 bytes)

allocated by malloc.• After the above statement is executed, size of

memory is increased to 20 bytes and ptr points to first byte.

• If the extra memory is not available in a full stretch, then entire block starting from first byte is shifted to some other location and new address of first byte is returned to ptr.

Freeing memory:• Memory allocated using malloc,calloc or realloc must

be freed at the end of program or else this memory cannot be used by other programs.

• Freeing is done free() function.• Ex: free(ptr);

Array of pointers

• Ragged array• Ex: 32 18 24• 13 11 6 12 42 19 14• 22• 13 3 14• 11 18

Array of pointers

• int **table=(int **)calloc(5,sizeof(int*));• table[0]= (int *)calloc(4,sizeof(int));• table[1]= (int *)calloc(7,sizeof(int));• table[2]= (int *)calloc(1,sizeof(int));• table[3]= (int *)calloc(3,sizeof(int));• table[4]= (int *)calloc(2,sizeof(int));

• 1.Write a program to create ,fill and print a table.

• 2. For the above program add functions which compute rowmax,rowmin,rowaverage for each row.