180 likes | 356 Views
POINTERS. PRESENTED BY: SANTOSH K DEVAL, PGT (CS), K. V. KIMIN. x. 3310. 386. POINTERS. Introduction A pointer is a variable which holds a memory address. Any variable declared in a program has two components . Address of the variable Value stored in the variable
E N D
POINTERS PRESENTED BY: SANTOSH K DEVAL, PGT (CS), K. V. KIMIN SKDeval
x 3310 386 POINTERS • Introduction • A pointer is a variable which holds a memory address. • Any variable declared in a program has two components . • Address of the variable • Value stored in the variable • For example - int x = 386 ; x is the name and 3310 is the address of memory location where value 386 is stored. SKDeval
Void pointers Pointers can also be declared as void. Void pointers can't be dereferenced without explicit casting. This is because the compiler can't determine the size of the object the pointer points to. Example: int x; float r; void *p = &x; /* p points to x */ int main (void) { *(int *) p = 2; p = &r; /* p points to r */ *(float *)p = 1.1; } SKDeval
Two special operators * and & are used with pointers. The & is a unary operator that returns the memory address of its operand for example – 1050 int i = 25 ; int *iptr; iptr = &i; 25 int i = 25 iptr = &i 1050 The & operator is used to take the address of a variable and its opposite the * operator is used to show the value at any address . A pointer variable must not remain uninitialized since uninitialized pointers cause the system crashing. int *iptr = NULL ; The zero pointer NULL is defined in the header file stddef.h . Note : Making a pointer point to incorrect type of data may lead to loss of information SKDeval
Pointer Arithmatic – Only two arithmetic operations , addition and subraction , may be performed on pointers. When you add 1 to a pointer , you are actually adding the size of whatever the pointer is pointing at. In pointer arithmatic , all pointers increase and decrease by the length of the data char *cptr ; int *iptr ; Base Address Adding 1 to a pointer actually adds the size of pointer’s base type . A pointer holds the address of the very first byte of the memory location where it is pointing to. The address of the first byte is known as Base Address SKDeval
DYNAMIC MEMORY ALLOCATION NEW OPERATOR In C++ , the pointer support dynamic memory allocation . Dynamic memory allocation means memory allocation at run time. In the case of array if the allocated size is more than the amount of data then the memory is wasted and if the size of array is less than the amount of data we cannot increase it at runtime. So if we wish to allocate memory as and when required , the new operator helps in this context . The syntax of the new operator is – Pointer_variable = new data_type ; char * cptr ; cptr = new char ; cptr = new char[21] ; This statement allocates 1 byte of memory and assigns the address to cptr . This statement allocates 21 bytes of memory and assigns the address to cptr . We can also allocate and initialize the memory in the following way – char * cptr = new char(‘J’) ; int * empno = new int [32] ; // some size must be specified . SKDeval
DELETE OPERATOR It is used to release or deallocate memory . The syntax of delete operator is – Delete pointer_variable ; For example – delete cptr ; delete [ ] empno ; MEMORY LEAKS • If we forget to delete the reserved memory allocated using new , an orphaned memory block ; a block that is still allocated but there is nothing referencing it, stjll exists. A function that allocates the memory to some object dynaimcally but does not deallocate it , consumes some space every time it is executed and has a bad effect on the system. This situation is called as a memory leak. Few reasons for leading to memory leak are – • Forgetting to delete something that has been dynamically allocated. • To check whether code is bypassing the delete statement. • To assign the new statement to already pointing pointer. SKDeval
Pointers And Arrays C++ interprets an array name as the address of its first element . Lets take an example int * a; int age[10] ; cout<<“Enter values for array age \n”; for(int i=0; i< 10 ; i++) cin>>age[i]; // assume a[0] entered as 11 a=age ; cout<“\n a points to” << *a <<“\n”; cout<<“age points to”<<*age<<“\n”; OUT PUT a points to 11 age points to 11 thus it is proved that the name of an array is actually a pointer that points to the first element of the array. SKDeval
j l i k 12 23 25 24 1060 1051 1062 1035 ARRAY OF POINTER Pointers also , may be arrayed like any other data type. To declare an array holding 10 int pointers , the declaration would be as follows – int *ip[10]; After this declaration, contiguous memory would be allocated for 10 pointers that can point to integers . ip[0] ip[1] ip[2] ip[3] ip[4] ip[5 ]ip[6] ip[7] ip[8] ip[9] Array ip → int i=12 , j=23 , k = 24 , l=25 ; ip[0] = &i ; ip[1] = &j ; ip[2] = &k ; ip[3] = &l ; 0 1 2 3 4 5 6 7 8 9 Array ip → SKDeval 2001 2003 2005 2007 2009 2011 2013 2015 2017 2019
i k j l 12 23 24 25 1060 1051 1035 1062 int i=12 , j=23 , k = 24 , l=25 ; ip[0] = &I ; ip[1] = &j ; ip[2] = &k ; ip[3] = &l ; 0 1 2 3 4 5 6 7 8 9 Array ip → 2001 2003 2005 2007 2009 2011 2013 2015 2017 2019 ip now is a pointer pointing to its first element of ip, ip is equal to address of ip[0], i.e 2001 *ip is the value of ip[0] is equal to 1035 *(*ip) is the value of *ip , is equal to 12 similarly **(ip + 3) is 31, because ip+3 points to 1062 and contents at 1062 are 31 Internally , addresses are resolved like this – s[0] = *(s+0) or *s or *(s) s[1] = *(s+1) ; s[2] = *(s+2) and so on s[0][0] = *(s[0] + 0) = *(*(s+0) + 0) = **s s[3][4] = *(s[3] + 4) = *(*(s+3) + 4) SKDeval
POINTERS AND STRINGS A String is a one-dimensional array of characters terminated by a null (‘\0’) char name[ ] = “POINTER” ; // Declaring a string for(int i=0 ; name[i]!=‘\0’ ; i++) cout <<“…..”<<name[i] ; alternatively , the same can be achieved using a character pointer also . char name[ ] = “POINTER” ; char *cp ; for(cp=name; *cp!=‘\0’; cp++) cout<<“…..”<< *cp ; Both the above given code segments produce the same output – ….P…..O…..I…..N…..T…..E…..R here *cp is the character pointer that is pointing to a string – name SKDeval
POINTERS AND FUNCTIONS • We know that the arguments in a function can can be passed by two methods- • Call by value (ii) Call by reference • In the first case the value changed in formal arguments not effect the actual argument supplied by main program but in second case the chaged value of formal arguments are reflected in actual arguments. The second method can be used in two ways – • By passing the reference (b) By passing the pointers REFERENCES AND POINTERS A reference is an alias name for a variable, for example – float value = 1700.25 ; float & amt = value ; here amt is declared as an alias name for the variable value. No separate memory is allocated for amt rather the variable value can now be accessed by two names value and amt. 1700.25 float value =1700.25 ; float &amt = value ; value amt SKDeval 6009
The following points should be taken into consideration while using references or aliases – • References can not be compared . • arithmetic operations are not permitted on references. • Array of references not allowed. • Addresses of a reference can not be taken. • It is due to the fact that the operation on alias is carried out on the data referred to by its reference and not on the alias itself. On the other hand , a pointer to a variable holds its memory address using which the memory area storing the data value of the variable can directly be accessed. float value =1700.25 ; float *fp = & value ; cout<<value ; cout<<amt ; cout<< *fp ; SKDeval
POINTERS AND CONST A constant Pointer Means that the pointer in consideration will always point to the same address, Its address can not be modified. A Pointer to constant refers to a pointer which is pointing to a symbolic constant. Using a pointer to a constant, the constant value(to which this pointer is pointing to) can not be modified. int n = 44 int *ptr=&n; ++(*ptr) int *const cptr=&n; ++(*cptr); ++cptr ; const int kn = 88 ; const int *ptrc = &kn; ++(*ptrc) ++ ptrc const int * const cptrc = &k ; ++(*cptrc); ++cptrc ; // and int // a pointer to integer n // valid // A const. pointer to an integer // valid … content increment // Invalid // a const. integer // a pointer to a const. integer // Invalid … // valid // A const pointer to a const. int // Invalid // Invalid SKDeval
POINTERS AND STRUCTURES The general form form of structure pointer is struct-name * struct-pointer ; struct date { short int dd , mm , yy ; } ; date *dt-ptr ; is same as struct date { short int dd , mm , yy ; } *dt_ptr ; or even we can write struct { short int dd , mm , yy ; } *dt_ptr ; Using Structure pointers , the members of structures are accessed using arrow operators -> . SKDeval
Functions Returning by Reference function may also return a reference for example – #include<iostream.h> #include<conio.h> int & min(int &a , int &b) { if(a<b) return a; else return b; } void main() { clrscr(); int x,y; x=10;y=20; cout<<endl<<x<<"\t"<<y; min(x,y)=-1; cout<<endl<<x<<"\t"<<y; getche(); } • OUTPUT • 20 • -1 20 SKDeval
POINTERS AND OBJECTS Just like other pointers pointer to object referred as object pointers are used – class-name *object-pointer ; for accessing the members of a class using an object pointer , the arrow operator -> is used instead of dot operator . Program to illustrate the use of object pointer #include<iostream.h> class Time { short int hh,mm,ss; public : Time() { hh=mm=ss=0 ; } void getdata (int I , int j , int k) { hh = I ; mm = j ; ss = k ; } void prndata(void) cout<<“\n Time is”<<hh<<“:”<<mm<<“:”<<ss<<“\n”; } }; void main() { Time * tp ; tp->getdata(15,10,17); cout<< “Printing member using object pointer”; tp->prndata() ; } OUTPUT Printing member using object pointer Time is 15:10:17 SKDeval
Give the output of the following program – void main() { int array[ ] = {12,30,4,5} int *arptr = array ; int value = *arptr ; cout<<value << ‘\t’; value = *arptr++ ; cout<<value<<‘\t’; //ptr will incr. value = (*arptr)++ ; cout<<value<<‘\t’; value = *arptr ; cout<<value<<‘\t’; value = *++arptr; cout<<value<<‘\t’; } 12 12 30 31 4 SKDeval