3 Class Pointers

Post on 20-Jul-2016

35 views 1 download

description

cl

Transcript of 3 Class Pointers

1

POINTERS• Pointer is a variable that contains the address

of an another variable.• A pointer is an address of a storage location,

By convention, zero represents the "null" pointer.

• The size of a pointer depends on the amount of memory to be addressed.

• By default pointer size is 2 bytes• A 16-bit pointer can address 64K locations.• A 32-bit pointer can address 4 trillion locations.• Pointer is used to access memory and

manipulate addresses.• Syntax: <datatype> *<pointer name>

• Why use pointers?• Pointers can be used as variable length

arrays.• Pointers can be used for advanced data

structures.• Pointers can be "cheaper" to pass around a

program.• If we want to pass a huge struct or array, it’s

easier to pass a pointer than the whole thing.• In general, pointers allow cleaner, more

compact code.

Pointer Types• Wild pointers arise when a pointer is used prior to

initialization to some known state.• Null pointer is a pointer which points to no where. • Void Pointer is also called as a Generic Pointer,

which can store the address of any variable . • Dangling pointer (C++) arise when an object is

deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.

• & - address of operator / referencing operator• * - value at address operator / Dereferencing

Operator.

4

Pointer Variablesint v; // defines variable v of type intint w; // defines variable w of type intint *p; // defines variable p of type pointer to intp=&v; // assigns address of v to pointer pv=3; // assigns value 3 to v*p=7; // assigns value 7 to vp=&w; // assigns address of w to pointer p*p=12; // assigns value 12 to w

• Using the indirection operator *p to access the contents of a variable is called indirect addressing or dereferencing the pointer

5

• Examples of pointer declarations:

int *a;float *b;char *c;FILE *fptr;

• The asterisk, when used as above in the declaration, tells the compiler that the variable is to be a pointer, and the type of data that the pointer points to, but NOT the name of the variable pointed to.

6

Use of & and *• When is & used?

• When is * used?

• & -- "address operator" which gives or produces the memory address of a data variable.

• * -- "dereferencing operator" which provides the contents in the memory location specified by a pointer

• Permissible operations with pointers• Adding a value to the pointer • Subtracting a value from the pointer• Incrementing a pointer• Decrementing a pointer

• Not-permissible operations with pointers• Two pointers can’t be added.• Multiplication, Division can’t be done between

any two pointers.

Wap to find pointer Addition• #include<stdio.h>

main(){

int a,b,c,*p,*q;clrscr();printf ("Enter a,b values:");scanf ("%d%d", &a, &b);p=&a;q=&b;c=*p+*q;printf("Addition=%d", c);getch();

}

• #include<stdio.h>main(){ int a,b,c,d,e,f,*p,*q;clrscr();printf("Enter a,b values:");scanf("%d%d",&a,&b);p=&a;q=&b;c=--*q;d=*q--;e=++*p;f=*p++;printf("\n pre decrement=%d", c);printf("\n post decrement=%d", d);printf("\n pre increment=%d", e);printf("\n post increment=%d", f);getch();}

Wap to print address of the pointers• #include<stdio.h>

main(){

int a,b,c,*p,*q;clrscr();printf("Enter a,b values:");scanf("%d%d",&a,&b);p=&a;q=&b;printf("Pointers Address=%u %u",p,q);printf(“\n Pointer values =%d %d”,a,b);getch();

}

WHAT IS OUTPUT OF THIS PGM

• #include <stdio.h>int main(){ int i,j; int *p; /* a pointer to an integer */ p = &i; *p=5; j=i; printf("%d %d %d\n", i, j, *p); getch();}

12

*/Factorial of a given number using pointers*/

• main(){ int n,factorial;printf(“enter a number”);scanf(“%d”,&n);factcompute(n,&factorial);printf(“the factorial of %d”,n,factorial);}factcompute(a,b)int a,*b;{int m; *b=1;for(m=1;m<=a;m++)*b=*b*m;}

Wap to swap numbers using third variable• #include<stdio.h>

main(){

int *p,*q,a,b,temp;clrscr();printf("Enter a,b values:");scanf("%d%d",&a,&b);p=&a;q=&b;temp=*p;*p=*q;*q=temp;printf("After Swapping a=%d b=%d",a,b);getch();

}

Wap to swap numbers without using third variable• #include<stdio.h>

main(){

int *p,*q,a,b,temp;clrscr();printf("Enter a,b values:");scanf("%d%d",&a,&b);p=&a;q=&b;*p=*p + *q;*q=*p - *q;*p=*p - *q;printf("After Swapping a=%d b=%d",a,b);getch();

}

15

Pointers as Function Arguments• Call by reference for arguments that may be altered

by the function.• Call by value is appropriate for small arguments

that should not be altered by the function.• Call by constant reference for large arguments that

should not be altered by the function– by value : void f(int x);– by reference : void f(int* x);

• In pass-by-value the function obtains only a local copy of the variable, so that changes to the local variable have no impact on the argument with which the function was invoked.

• In pass-by-reference the function manipulates the original variable rather than merely its copy

16

Pass-by-Referencevoid swap( double* ptr1, double* ptr2){ double tmp=*ptr1; *ptr1=*ptr2; /* de-referencing pointer */ *ptr2=tmp;}int main(){ double a=3.0; double b=5.0 swap(&a, &b); /* call by reference using the addresses of a and b */ printf(“a=%lf, b=%lf\n”, a,b);}

Pointers to Pointers• It is possible and often useful to create

pointers to pointers. • This technique is sometimes called a handle,

and is useful in certain situations where the operating system wants to be able to move blocks of memory on the heap around at its discretion.

• The following example demonstrates a pointer to a pointer:

• int **p; int *q; p = (int **)malloc(sizeof(int *)); *p = (int *)malloc(sizeof(int)); **p = 12; q = *p; printf("%d\n", *q); free(q); free(p);

Memory Allocation1. malloc allocates memory, void *malloc(size_t size)

returns a pointer to a chunk of memory which is the size in bytes requested.

2. calloc allocates and clears a two-dimensional chunk of memory, void *calloc(size_t nmemb, size_t size) same as malloc but puts zeros in all bytes and asks for the number of elements and size of an element.

3. free returns previously allocated memory to the operating system, void free(void *ptr) deallocates a chunk of memory. Acts much like the delete operator.

4. realloc changes the size of previously allocated memory, void *realloc(void *ptr, size_t size) changes the size of the memory chunk point to by ptr to size bytes, prototypes found in the stdlib.h header file.

Example Memory Allocationvoid main() {

char *cptr;double *dblptr;struct Student *stuptr;/* equiv to cptr = new char[100]; */cptr = (char *) malloc(100);/* equiv to dlbptr = new double[100]; */dblptr = (double *) malloc(sizeof(double) * 100);/* equiv to stuptr = new Student[100]; */stuptr = (struct Student *) malloc( sizeof( struct Student) * 100);

}

• Advantages of Pointers:– Makes program works faster as they are directly dealing with

addresses.– Arrays can be easily accessed using pointers– Call by Reference can be achieved using Pointers– Dynamic memory allocation can be achieved– Complex Declarations are possible in Pointers. – Passing arguments to functions when the function needs to

modify the original argument.– Passing arrays and strings to functions– Obtaining memory from the system– Creating data structures such as linked lists.– Function cannot return more than one value. But when the

same function can modify many pointer variables and function as if it is returning more than one variable.

– In the case of arrays, we can decide the size of the array at runtime by allocating the necessary space.

Disadvantages • Pointers are probably the single largest

source of bugs in software, so be careful anytime you deal with them.

• Dangling reference (premature free)• Memory leaks (tardy free).• If sufficient memory is not available during

runtime for the storage of pointers, the program may crash (least possible).