[1] ~~~~~~~~~~~~~~~~~ POINTER A pointers is a variable that holds a memory address, usually the location of another variable in memory. IMPORTANT FEATURES OF POINTERS (1) provide the means through which the memory location of variables can be directly accessed and they can be manipulated at wish. (2) support C++ s dynamic allocation routines. (3) improve the efficiency of certain routines. Note: Every byte of computer s memory (internal) has an address. For 280 KB = 280*1024 bytes = 286720 bytes. addresses of each bytes is allocated as mentioned in the figure: MEMORY ADDRESS 0 1 2 3 4 _- - - - - - - - - - - - - - - - - 286717 286718 286719 REPRESENTATION OF BYTES AND ITS ADDRESSES 286719 286718 286717 - - - 4 3 2 1 0 MEMORY ADDRESS C++ COMCEPTUAL MEMEORY MAP After the compilation of a program, C++ creates four logically distinct regions of memory for four distinct specific work. It is clear from the figure: GLOBAL VARIABLES STACK HEAP PROGRAM CODE This region holds return addresses at function call and arguments passed to functions while program is being executed. The stack also holds the current state of CPU. This region holds the free memory from which chunks of memory are allocated for dynamic memory allocation. This region is also known as Free Store which is unnamed and unutilized. This region holds the global variable of the program. Global variables remain in memory till the program continues. This region holds the compiled code of program. Each instruction & function of program starts at some certain address. C++ CONCEPTUAL MEMORY MAP MEMORY ALLOCATION Every data and instruction that are being executed are allocated some area in the main (internal) memory. This is done in two ways known as: (i) static memory allocation, and (ii) dynamic memory allocation STATIC MEMORY ALLOCATION When the memory allocation is known beforehand and is allocated at compile time, it is called static memory allocation. For example, when we declare variable as: short rate ; then for the variable rate 2 bytes is allocated at compilation time as short has 2 byte range. Thus it is static memory allocation. DYNAMIC MEMORY ALLOCATION When the memory is allocated as and when required during the program runtime, it is called dynamic memory allocation. The dynamic memory allocation is done with the help of two operators new and delete. Notes: 1 An object s life-time is (stay time in memory) is known as its extent. 2 Global variables or variables having file-scope are said to have static extent. 3 Variable having local scope are said to Page-1
~~~~~~~~~~~~~~~~~ have local extent. 4 Local variables with static specifier have static extent. 5 Objects, for which memory is dynamically allocated, have dynamic extent. DECLARATION AND INITIALIZATION OF POINTERS For declaring a pointer general syntax is: type *var_name ; Example: int *iptr ; char *cptr ; float *fptr ; Variable Address Meaning Let us try to understand the following code snippet: i 27 1050 i = 27, int *iptr int i = 27, j ; //declaration of int variable i. 1051 int *Iptr ; //declaration of int pointer. iptr 1050 1052 iptr = &i iptr = &i ;//iptr is pointing to mem. location of i. j 27 1053 j = i j = i ; Notes: 1 iptr = &i ; implies that iptr assigns address of i. 2 j = *iptr ; implies that j assigns the value at the address pointed by iptr. POINTER ARITHMETICS Only two arithmetic operation addition and subtraction may be performed on the pointers. Thus all pointers increase or decrease by the length of data type they point to. This is clear from the following example: char *cpt ; //note that char is of one byte int *iptr ; // note that int is of two byte [2] cptr ctpt+1 1001 1002 1003 1004 1005 1006 1007 1008 DYNAMIC ALLOCATION OPERATORS (new, delete) The operator new is used to create objects of all types including a class name. General form is: Pointer_variable = new data_type; Ex: iptr = new int; //allocates memory for int type. cptr = new char; // allocates memory for char type. fptr = new float; //allocates memory for float type. Once a pointer points to newly allocated memory, data values can be stored their using * operator, as is shown below: *cptr= a ; *fptr = 17.744; The new allocated memory can also be initialized at the time of allocation itself as shown below: char *cptr = new char( a ); float *fptr = new float(17.744); The operator new can also allocate memory for user-defined types like structures, arrays, and classes, as is shown below: Pointer_variable = new int[size] ; Ex: int *value = new int[17] ; It will create memory space from the free store for an array of 17 integers. Note: Array size must be supplied when new is used for array creation. Allocation of space for 2D array using new operator can be understood from the following program snippet: int *val; r,c; cout<< Enter dimensions (No. of row & column): ; cin>>r>>c; val = new int[r*c]; For reading the elements of this 2D-array we provide the code as shown below: for(int i=0; i<c; i++) { cout<< Enter elements in row <<(i+1)<< : ; for (int j=0; j<c; j++) { cin>>val[i*c+j]; //see here A[i][j] is replaced by A[i*c+j] iptr iptr+1 iptr+2 Address Page-2
~~~~~~~~~~~~~~~~~ The lifetime of an object created by new is not limited to the scope in which it is created. It lives in the memory until clearly deleted with the help of delete operator, so that memory may be freed for reuse. The general form for delete is: delete pointer_variable; Ex: delete ipter; delete[size] pointer variable Let us understand the working of new and delete operator by following program: [3] Program: Program to create two array to store roll numbers and marks of some students, whose number would be known at run time(illustration of free store operation.) #include<iostreatm.h> int *rollno; //declaration of int pointer for rollno array float *marks; //declaration of float pointer for marks array { int size; cout<< How many element are there in the array?:\ ; cin>>size; rollno = new int[size]; //dynamic allocation of rollno array marks = mew float[size];//dynamic allocation of marks array //Checking of availability of memory. if((!rollno) (!marks)) //if rollno or marks is null pointer { cout<< Out of Memory! Aborting! ; return 1; //Read in values in the array elements for (int i=0; i<size; i++) { cout<<enter rollno and marks for student <<(i+1)<< \n ; cin>>rollno[i]>>marks[i]; //Display the array contents cout<< \troll no\tmarks\n ; for(i=0; i<size; i++) cout<< t <<rollno[i] << t\t <<marks[i]<< \n ; delete[ ]rollno; delete[ ]marks; ORPHNED MEMORY BLOCK AND MEMORY LEAK A block of memory dynamically allocated with the help of new operator and nit deallocated with the help of delete operator is called orphaned memory block. A program containing orphaned memory block xonsumes some amout of memory, every time the program is executed/run, which causes adverse effect on the system. This situation is called memory leak. POSSIBLE CAUSES/REASONS OF MEMORY LEAK 1 Improper use of new and delete operator. 2 Forgetting to delete something dynamically allocted. 3 Bypassing the delete statement by programmer. 4 Assigning the result of a new statement to a pointer which already points to an allocated object. POINTERS AND ARRAY and arrays are closely related in C++. The name of an array is a pointer pointing to the first element of the array. The array-name gives the base address of the array. Naturally arr-name+1 will give the address of second element, arry-name +2 will give the address of third element, and so on. Thus, to print the fourth element of array age we can use either of the following: cout <<age[3]; cout <<*(age+3); Page-3
[4] ~~~~~~~~~~~~~~~~~ Note that: *(age+3) Value at the address of (age+3) Value at the (address of age +3) Value at the address of (1001 +3) Value at the address of 1004 25. ARRAY OF POINTERS The syntax for the declaration of array of pointers is: Data_type *pointer_name[size]; Ex: float *fp[7];// array of 7 float pointers This declaration means - ip is an array of 7 elements and each element is a points to a elements and each element is a pointer to a variable of float type. Let us understand this by following program: PROGRAM Illustration of concept of array of pointers. # { int *ip[4] //initialization of array pointers pointing to 4 integer values. int fe = 16, fi = 25, fo = 34, fum = 43; ip[0]=&fe; ip[1]=&fi; ip[2]=&fo; ip[3]=&fum; //Display of values pointed by pointers for(i=0; i<4; i++) { cout<< The pointer ip[ <<i<< ] points to <<*ip[i]<< \n ; //Display fo addresses stored in the array cout<< The base address of array ip is <<ip<< \n ; for(i=0; i<4; i++) { cout<< Address of ip[ <<i<< ]is <<ip[i]<< \n ; FORMULAE FOR THE SOULTION TO THE ARRAY OF POINTERS value address age[6] 60 1007 age[5] age[4 age[3] age[2] age[1] age[0] 40 32 25 33 28 26 1006 1005 1004 1003 1002 1001 1 *A = *(A) = *(A + 0) = A[0] **A = *(*(A = 0)) = *(A[0] + 0) *(A + 1) = A[1] 2 *(*A + 1) = *(A[0] + 1) = A[0][1] *(A + i) = A[i] *(*(A + i) + j) = *(A[i] + j) = A[i][j] Let us understand the use of pointer arithmetic with the help of following pgroam: Program-1 : for the manipulation of 2-d array #inclued<iostream.h> { int x[3][5] = {{1, 2, 3, 4, 5, {6, 7, 8, 9, 10, {11, 12, 13, 14, 15 ; int *n = &x[0][0]; cout<< (1) *(*(x + 2) + 1) \t = << *(*(x + 2) + 1) <<endl ; cout<< (2) *(*x + 2)+ 5 \t = << *(*x + 2) + 5 <<endl ; cout<< (3) *(*(x + 1)) \t = << *(*(x + 1) ) <<endl ; cout<< (4) *(*(x) + 2) + 1 \t = << *(*(x) + 2) + 1) <<endl ; cout<< (5) *(*(x + 1) + 3) \t = << *(*(x + 1) + 3) <<endl ; cout<< (6) *n \t \t = << *n <<endl ; cout<< (7) *(n + 2) \t = << *(n + 2) <<endl ; cout<< (8) (*(n + 3) + 1) \t = << (*(n + 3) + 1) <<endl ; cout<< (9) *(n + 5) + 1 \t = << *(n + 5) + 1 <<endl ; Page-4
[5] ~~~~~~~~~~~~~~~~~ cout<< (10) ++*n \t = << ++*n <<endl ; [OUPTPUT HINT : 12, 8, 6, 4, 9, 1, 3, 5, 7, 2] Program-2 : for the manipulation of ARRAY OF POINTERS #inclued<iostream.h> { int x[3][5] = {{18, 20, 13, 24, 35, {7, 8, 6, 19, 10, {19, 22, 30, 21, 15 ; int *n = &x[0][0]; cout<< (1) (*(n + 3) + 1) \t = << (*(n + 3) + 1) <<endl ; cout<< (2) *(n + 2)+ 5 \t = << *(n + 2) + 5 <<endl ; cout<< (3) *(*x + 2) + 5 \t = << *(*x + 2) + 5 <<endl ; cout<< (4) ++*n \t = << ++*n <<endl ; cout<< (5) *(*(x) + 2) + 1 \t = << *(*(x) + 2) + 1 <<endl ; cout<< (6) *n \t \t = << *n <<endl ; cout<< (7) *(*(x + 2) +1) \t = << *(*(x + 2) +1) <<endl ; cout<< (8) *(*(x + 1) +3) \t = << *(*(x + 1) +3) <<endl ; cout<< (9) *(*(x + 1)) \t = << *(*(x + 1)) <<endl ; cout<< (10) *(n + 5) +1 << *(n + 5) +1 <<endl ; [OUPTPUT HINT : 35, 13, 15, 19, 14, 18, 22, 19, 7, 8] POINTERS And STRINGS We know that group of character of any length is known as string, last character being a null character(\0). A pointer can point to a string by following declaration: char name[ ]= Self-Help ; char *cp; // declaring a character pointer for (cp=name; *cp!= \0 ; cp++) cout<<*cp; Ex: What would be the output of following: #include<iostream.h> { char *ptr; ptr = nice ; cout<<++*ptr; Notes: Several strings can be stored as: char *neme[ ]={ chair, table, desk ; POINTER AND FUNCTIONS INVOKING FUNCTION BY PASSING THE REFERENCE Program : To swap values of two variables #include<iostream.h> { void swap(int&, int&); //FP int a=7, b=4; cout<< Original value of a= <<a<< and b= <<b<<endl; swap(a,b);//fc by reference cout<< Swapped value of a= <<a << and b= <<b<<endl; void swap(int &x, int &y) //FD { int temp; temp = x ; x = y; y = temp; Page-5
~~~~~~~~~~~~~~~~~ INVOKING FUNCTION BY PASSING THE POINTER Program : To swap values of two variable by passing pointer #include<iostream.h> { void swap(int *x, int*y); //FP int a=7, b=4; cout<< Original value of a= <<a<< and b= <<b<<endl; swap(&a, &b); cout<< Swapped value of a= << a << and b = << b << endl ; void swap(int *x, int *y) //FD { int temp; temp = *x ; *x = *y; *y = temp; [6] FUNCTION RETURNING POINTERS PROGRAM : TO ILLUSTRATE A FUNCTION RETURNING A POINTER. # include <iostream.h> int *big (int&, int&) ;//function prototype of a function returning a pointer void main ( ) { int a, b, *c ; cont<< enter two integers : << endl ; cin >>a, b ; c = big(a, b) ; //function call cout<< The bigger value is << *c <<endl ; //note that in FC we calculated the // value of c but display is given by *c int *big(int &x, int &y) //function def. of a function returning a pointer { if(x >y) return (&x) ; else return (&y) ; OUTPUT : Enter two integers 7 13 The bigger value is 13 STRUCTURE POINTER The pointer to a structure is called structure pointer. General form of declaration of structure pointer is: sturct-name *sturct-pointer; Ex: sturct date{short int dd, mm, yy ; ; date *dptr; // dptr = date-pointer OR struct date{short int dd, mm, yy ; *dptr; // sturct-type & sturct pointer is combined. Using structure pointer, the memory of structures are accessed by using arrow operator (->) as, dptr ->dd; dptr ->mm; dptr ->yy; Program : To illustrate the use of structure-pointer. #include<iostream.h> { sturct date{dhort int dd, mm, yy ; join-date = {10,09,07 ; date *dptr; dptr=&join-date; cout<< Display of structure elements using structure variable: ; cout<< join-date.dd<< - << join-date.mm << - << join-date.yy ; cout<< Display of structure elements using structure pointer\n ; cout<<dptr->dd<< - <<dptr->mm << - <<dptr->yy<<endl; There are two primary uses of structure pointers: (i) to generate a call by reference to a function (ii) to create dynamic data structure such as linked list, stacks, queues, trees etc. Page-6
[7] ~~~~~~~~~~~~~~~~~ SELF-REFERENTIAL STRUCTURE A structure having a member element referring to the structure itself is called self-referential structure. It is clear from the following figure: DYANAMIC STURCTURE The structure for which memory is allocated dynamically is called synamic structure. The new operator is used for creating dyanamic sturctue, as is given below: Struct-pointer=new struct-type; Ex: contest *cptr;//candidate pointer cptr= new contest; A dynamic structure must be deallocated after its use is over. It can be done as; delete cptr; OBJECT POINTER A pointer pointing to object called object pointer. It declared as: class-name *object-pointer; Ex: class something{ int a,b; public:..;; {something s1;//declaring an object something *ps1;//declaring object pointer.. THIS POINTER This pointer is an special pointer which stores the address of the object that is currently invoking(executing) a member function of a class. Program : To display the address of object using this pointer #include<iostream.h> class sample{ private: int x; public: void display( );; void sample::display( ) { cout<< Object s address = <<this<<endl; { sample obj1, obj2, obj3; obj1.display( ); obj2.display( ); obj3.display( ); OUTPUT: Object s address = ox24e0fff2 Object s address = ox24e0fff0 Object s address = ox24e0ffee Demonstration : Of how the this pointer is used to access the member data of a class. #include<iostream.h> class sample{ private: int x; public: void display( ) ; ; void sample::display( ) { this ->x = 20; cout<< Content of x = <<this->x<<endl; { sample obj1; obj1.display( ); [OUTPUT: Content of x = 20] HOME-WORK Problem: 4, 8, 12, 20, 24 and Find the output of following program: #include<iostream.h> { int x[3][5]={{18,20,13,24,35, {7,8,6,19,10, {19,22,30,21,15 int *n=&x[0][0]; cout<< (1)\t <<(*(n+3)+1)<<endl; cout<< (2)\t <<*(n+2)<<endl; cout<< (3)\t <<*(*x+2)+5<<endl; cout<< (4)\t <<++*n<<endl; cout<< (5)\t <<*(*(x)+2)+1<<endl; cout<< (6)\t <<*n<<endl; cout<< (7)\t <<(*(x+2)+1)<<endl; cout<< (8)\t <<(*(x+1)+3)<<endl; cout<< (9)\t <<(*(x+1))<<endl; cout<< (10)\t <<*(n+5)+1<<endl; Page-7